Mongoose - Anyway, to prevent the middleware from being intercepted from execution under certain conditions (for example, saved as a subdocument)?

I have a Foo scheme that has pre and post save hooks.

For the special debugging application that I am writing, I grab all active Foo objects. Then save them as a subdocument as part of the story outline.

When I save it as part of a subdocument, I do not want my hooks to be pre / post save executed.

What is the best way to handle this?

I would like not to retrieve all the data from the Foo object and then save it in a new object other than mongoose.

+7
mongodb mongoose
source share
1 answer

You can define a field for your Foo object, for example hookEnabled , and you can check it in your hook function. Let me give an example:

 Foo = new Schema({ ... hookEnabled:{ type: Boolean, required: false, default: true } ... }); 

And in your hook;

 Foo.pre('save', function(next){ self = this if (self.hookEnabled) { // dou your job here next(); } else { // do nothing next(); } }); 

Before calling the save function, you can set the hookEnabled field to false,

 var fooModel = new Foo(); fooModel.hookEnabled = false; 

Hope this helps

+8
source share

All Articles