Does Mongoose provide access to previous value of property in pre('save')?

前端 未结 4 740
南笙
南笙 2020-12-14 08:23

I\'d like to compare the new/incoming value of a property with the previous value of that property (what is currently saved in the db) within a pre(\'save\') mi

4条回答
  •  感动是毒
    2020-12-14 08:55

    The accepted answer works very nicely. An alternative syntax can also be used, with the setter inline with the Schema definition:

    var Person = new mongoose.Schema({
      name: {
        type: String,
        set: function(name) {
          this._previousName = this.name;
          return name;
        }
    });
    
    Person.pre('save', function (next) {
      var previousName = this._previousName;
      if(someCondition) {
        ...
      }
      next();
    });
    

提交回复
热议问题