Mongoose是否可以在pre('save')中访问以前的属性值?

sma*_*ott 22 mongoose mongodb

我想将属性的新/传入值与pre('save')中间件中该属性的先前值(当前保存在数据库中的值)进行比较.

Mongoose是否提供了这样做的设施?

aar*_*ann 24

Mongoose允许您配置自定义setter,您可以在其中进行比较.pre('save')本身不会给你你需要的东西,但是在一起:

schema.path('name').set(function (newVal) {
  var originalVal = this.name;
  if (someThing) {
    this._customState = true;
  }
});
schema.pre('save', function (next) {
  if (this._customState) {
    ...
  }
  next();
})
Run Code Online (Sandbox Code Playgroud)

  • 我是否需要执行此操作才能访问** validators **中的先前值?还是在验证程序中有更简单的方法? (2认同)
  • 我不知道这以前是否有效,但现在不再有效了。this.name 未定义 (2认同)

Tom*_*cer 23

接受的答案很有效.也可以使用替代语法,setter与Schema定义内联:

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();
});
Run Code Online (Sandbox Code Playgroud)