Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Anyway to prevent middleware save hooks from executing under certain conditions (e.g. being saved as subdocument)?

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.

like image 389
blak3r Avatar asked Oct 29 '13 22:10

blak3r


People also ask

What are Mongoose Middlewares?

Mongoose middleware are functions that can intercept the process of the init , validate , save , and remove instance methods. Middleware are executed at the instance level and have two types: pre middleware and post middleware.

What are middleware hooks?

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. The hooks are specified on RxCollection-level and help to create a clear what-happens-when-structure of your code. Hooks can be defined to run parallel or as series one after another.

What is the difference between model and schema in Mongoose?

Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What is pre hook in Mongoose?

On my journey to explore MongoDB and Mongoose's powerful features over the years, I encountered something called pre and post hooks, few years back. They are simple yet powerful tools with which you can manipulate model instances, queries, perform validation before or after an intended database operation etc.


1 Answers

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

like image 53
Hüseyin BABAL Avatar answered Sep 19 '22 07:09

Hüseyin BABAL