Find if object is modified in pre-save hook mongoose

I am trying to find if an object is modified in pre-storage and performs 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 do not change anything!

+5
source share
1 answer

First of all, you do not need the original object. You can access it in pre with this . The second time, post hook is executed only after all pre hooks have been completed, so your code does not make sense at all ( check mongoose docs ).

You can do the verification by checking isModified in your pre trick and generally remove the post hook.

 OrderSchema.pre('save', function(next) { if(!this.isModified()){ //not modified } next(); }); 

Update

To check if a property has been changed, pass the property name as a parameter to the isModified function:

 if (this.isModified("some-property")) { // do something } 
+9
source

Source: https://habr.com/ru/post/1210350/


All Articles