我想将属性的新/传入值与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)
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)
| 归档时间: |
|
| 查看次数: |
9864 次 |
| 最近记录: |