26

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

Mongoose 是否提供了执行此操作的工具?

4

4 回答 4

35

接受的答案非常有效。也可以使用另一种语法,将 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();
});
于 2015-05-15T09:11:29.617 回答
27

Mongoose 允许您配置进行比较的自定义设置器。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();
})
于 2012-07-18T17:19:06.333 回答
2

我一直在寻找一种解决方案来检测多个领域中任何一个领域的变化。由于看起来您无法为完整架构创建设置器,因此我使用了虚拟属性。我只在几个地方更新记录,所以对于这种情况,这是一个相当有效的解决方案:

Person.virtual('previousDoc').get(function() {
  return this._previousDoc;
}).set(function(value) {
    this._previousDoc = value;
});

假设您的 Person 移动了,您需要更新他的地址:

const person = await Person.findOne({firstName: "John", lastName: "Doe"});
person.previousDoc = person.toObject();  // create a deep copy of the previous doc
person.address = "123 Stack Road";
person.city = "Overflow";
person.state = "CA";
person.save();

然后在您的预挂钩中,您只需要引用 _previousDoc 的属性,例如:

// fallback to empty object in case you don't always want to check the previous state
const previous = this._previousDoc || {};

if (this.address !== previous.address) {
    // do something
}

// you could also assign custom properties to _previousDoc that are not in your schema to allow further customization
if (previous.userAddressChange) {

} else if (previous.adminAddressChange) {

}
于 2019-06-15T04:26:26.110 回答
0

老实说,我尝试了此处发布的解决方案,但我必须创建一个函数,将旧值存储在数组中,保存值,然后查看差异。

// Stores all of the old values of the instance into oldValues
const oldValues = {};
for (let key of Object.keys(input)) {
    if (self[key] != undefined) {
        oldValues[key] = self[key].toString();
    }

    // Saves the input values to the instance
    self[key] = input[key];
}

yield self.save();


for (let key of Object.keys(newValues)) {
    if (oldValues[key] != newValues[key]) {
       // Do what you need to do
    }
}
于 2016-06-19T14:41:59.760 回答