Last Updated: February 25, 2016
·
1.485K
· omarsmak

Disable the parent hooks in Mongoose when saving subdocuments

If you have any hooks under your parent schema (pre save, for example), most likely they will be triggered every time you intend to save the subdocuments which is not preferable, especially if you have one time data validation set.

To workaround this issue, you can add a hook flag under your parent schema. For example:

var parentSchema = new Schema({
...
hookEnabled: {
    type: Boolean, 
    default: true
    }
});

In the hook itself, you can have it like this:

    parentSchema.pre('save', function(next, done){
    var self = this;
    if(self.hookEnabled){
//If the hook is enabled, do your validation here
     } else {
//If the hook is disabled, skip
        next();
    }});

Then whenever you save the subdocuments, you can disable the hook:

var parent = mongoose.model('Parent');

...
parent.hookEnabled = false;
parent.save(function(err, doc){
...
});

Happy coding :)