8

I have a schema Foo which has pre and post save hooks.

For a special debugging application I'm writing, I grab all the active Foo objects. Then, save them as a subdocument as part of a History schema.

When I save it as part of the subdocument, I do not want my pre/post save hooks to execute.

What's the best way to handle this?

I'd like to avoid having to extract all the data from the Foo object then saving in an new non-mongoose object.

blak3r
  • 16,066
  • 16
  • 78
  • 98

2 Answers2

10

You can define a field to your Foo object like hookEnabled and you can check it in your hook function. Let me give you 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 save function, you can set hookEnabled field as false like,

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

Hope it helps

Hüseyin BABAL
  • 15,400
  • 4
  • 51
  • 73
  • 2
    I know this is old, but is there a way to do this with `findOneAndUpdate`? The context of `this` in the callback is the Mongoose query and not the document. Having a spot of trouble.. – Chris Wright Jun 15 '15 at 19:23
  • Isn't this store the hookEnabled field in the db? – papaiatis Jun 08 '16 at 19:10
  • @papaiatis yes, that field will be saved to db as `true` by default if you do not explicitly provide `hookEnabled` value – Hüseyin BABAL Jun 10 '16 at 12:23
  • 1
    It might make more sense to use virtual getter and setter functions for this rather than storing this in the database. Saving `hookEnabled` to the database seems non-beneficial and pollutes the data. – Chad Johnson Feb 03 '18 at 07:57
  • I recommend avoiding this technique as you could end up with a race condition with multiple concurrent requests. – Clayton Gulick Feb 05 '21 at 23:39
  • Could you elaborate how such a race condition might occur in this specific case? – user2495085 Jul 27 '22 at 16:07
0

This question is quite old, but I figured it's better pointing that out now than never. Mongoose includes in the Document object a property called $locals that is a type of anything-goes field. They even say in the documentation that one good use for it is to pass information to to middleware

https://mongoosejs.com/docs/api/document.html#document_Document-$locals

user2921009
  • 711
  • 1
  • 10
  • 21