查找是否在预保存的钩子猫鼬中更改了对象 [英] Find if object is changed in pre-save hook mongoose

查看:65
本文介绍了查找是否在预保存的钩子猫鼬中更改了对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找对象是否在预保存中发生了更改,并相应地执行了一些操作. 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对象.您可以通过thispre挂钩中对其进行访问.其次,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
}

这篇关于查找是否在预保存的钩子猫鼬中更改了对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆