Mongoose Pre-Save Hook is Firing, but Not Saving Additional Field (NOT using model.update)

前端 未结 1 967
执念已碎
执念已碎 2021-01-14 12:42

I am attempting to implement a counter in my schema to grab the next issue number. I have implemented it as a hook pre-save hook in Mongoose, and everything looks fine...

相关标签:
1条回答
  • 2021-01-14 13:24

    You are missing out on the this context here,

    .pre('save', function(next) {
      Project.findOne({_id: this.project}).select('numberSeq').exec(function(err, doc) {
        if (err) {
          console.log(err);
        }
        console.log('pre-save hook firing');
          this.number = doc.numberSeq;
          console.log(this.number);
          next();
        });
    })
    

    where you say:

    this.number = doc.numberSeq;
    console.log(this.number);
    

    actually refers to the callback function of the findOne query, thus you are ending up with the right console.log and wrong data inserted.

    you can remember this context of the pre save hook, and later update the number using that context inside the callback. like below:

    .pre('save', function(next) {
      var tat=this;
      Project.findOne({_id: this.project}).select('numberSeq').exec(function(err, doc) {
        if (err) {
          console.log(err);
        }
        console.log('pre-save hook firing');
          tat.number = doc.numberSeq;
          console.log(tat.number);
          next();
        });
    })
    
    0 讨论(0)
提交回复
热议问题