Find if object is changed in pre-save hook mongoose

14,847

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
}
Share:
14,847

Related videos on Youtube

raju
Author by

raju

Updated on September 14, 2022

Comments

  • raju
    raju over 1 year

    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!

  • andersfylling
    andersfylling about 8 years
    Any idea how to check a object variable? eg. this.something.isModified() gives me an undefined error
  • andersfylling
    andersfylling about 8 years
    Have you checked that it works? Cause I get an error and this post says otherwise: stackoverflow.com/questions/31173516/…
  • Vsevolod Goloviznin
    Vsevolod Goloviznin about 8 years
  • andersfylling
    andersfylling about 8 years
    Document and Schema doesnt share the same methods
  • Vsevolod Goloviznin
    Vsevolod Goloviznin about 8 years
    @sciencefyll what mongoose version are you using? I've just checked this code with v4.2.5 and this.isModified("property") is working fine.
  • andersfylling
    andersfylling about 8 years
    4.4.12. I'm going to create a new question addressing this, as I might be doing something horrible wrong without realising it.
  • andersfylling
    andersfylling about 8 years
  • Suhayb
    Suhayb over 5 years
    this in schema pre refers to model not doc, though isModified() wont work unless you change the hook status to post then this became a doc