Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

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

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') middleware.

Does Mongoose provide a facility for doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...