Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if object is changed in pre-save hook mongoose

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();
});

It returns false even when I don't change anything!

like image 267
raju Avatar asked Jan 04 '15 10:01

raju


1 Answers

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).

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();
});

Update

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
}
like image 76
Vsevolod Goloviznin Avatar answered Sep 19 '22 04:09

Vsevolod Goloviznin