问题描述
我正在尝试查找对象是否在预保存中发生了更改,并相应地执行了一些操作. Followinfg是我的代码
I am trying to find if the object is changed in pre-save and do some actions accordingly. Followinfg is my code
var eql = require("deep-eql");
OrderSchema.post( 'init', function() {
this._original = this.toObject();
});
OrderSchema.pre('save', function(next) {
var original = this._original;
delete this._original;
if(eql(this, original)){
//do some actions
}
next();
});
即使我什么都没改变,它也会返回false!
It returns false even when I don't change anything!
推荐答案
首先,您根本不需要original
对象.您可以通过this
在pre
挂钩中对其进行访问.其次,post
挂钩仅在执行所有pre
挂钩之后才执行,因此您的代码根本没有任何意义(检查猫鼬文档).
First of all, you don't need the original
object at all. You can access it in the pre
hook via this
. Secondly post
hook executes only after all pre
hooks are executed, so your code doesn't make any sense at all (check mongoose docs).
您可以通过在pre
钩子,然后完全取下post
钩子.
You can do the check by checking isModified
in your pre
hook and remove the post
hook at all.
OrderSchema.pre('save', function(next) {
if(!this.isModified()){
//not modified
}
next();
});
更新
为了检查是否修改了某些属性,请将属性名称作为参数传递给isModified
函数:
In order to check if some property was modified, pass property name as a parameter to isModified
function:
if (this.isModified("some-property")) {
// do something
}
这篇关于查找是否在预保存的钩子猫鼬中更改了对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!