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
}
Related videos on Youtube
Author by
raju
Updated on September 14, 2022Comments
-
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 about 8 yearsAny idea how to check a object variable? eg. this.something.isModified() gives me an undefined error
-
andersfylling about 8 yearsHave you checked that it works? Cause I get an error and this post says otherwise: stackoverflow.com/questions/31173516/…
-
Vsevolod Goloviznin about 8 years@sciencefyll I was looking here: mongoosejs.com/docs/api.html#document_Document-isModified
-
andersfylling about 8 yearsDocument and Schema doesnt share the same methods
-
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 about 8 years4.4.12. I'm going to create a new question addressing this, as I might be doing something horrible wrong without realising it.
-
andersfylling about 8 yearsLet us continue this discussion in chat.
-
Suhayb over 5 yearsthis 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