Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which functions done/next are bound to in mongoos pre/save/(serial/parallel) middleware

Trying to understand mongoose middleware (pre/save/parallel) thru docs/blogs(Tim Casewell).

Based on http://mongoosejs.com/docs/middleware.html

var schema = new Schema(..);
schema.pre('save', true, function (next, done) {
  // calling next kicks off the next middleware in parallel
  next();
  doAsync(done);
});

The hooked method, in this case save, will not be executed until done is called by each middleware.

What is done/next bound to here? Can you please give a complete example of how to use it?

For eg: I use serial as follows:

myModel.save(function(err) {
  if (err) 
    console.error("Error Occured")
  else
    console.info("Document Stored");
});

Schema.pre('save', function(next) {
  if (!self.validateSomething()) {
    next(new Error());
  } else {
    next();
  }
});

What is next bound to here? It needs to be bound to something to get executed? I fail to understand which function(s) next/done are referring to?

If you could elaborate control flow for my code above, that would be a great help.

-------------This is just to elaborate my understanding (not part of question)------

   * On executing myModel.save(...)
   * Control Flow will be passed to pre/save
   * if self.validateSomething() fails,
     * Document will not be tried to be saved in DB
     * "Error Occurred" will be printed on console
   * if validation succeeds,
     * Control Flow should be passed to *somewhere* in Mongoose libs 
       * Document will be tried to save in DB
         * On Success, "Document saved" will be printed on the console
         * On Failure, "Error Occurred" will be printed on console
like image 239
GJain Avatar asked Jul 03 '13 19:07

GJain


1 Answers

They're bound to functions that provide flow control internally within Mongoose. Mongoose depends on hooks-js for its middleware functionality, see the source for more details.

For example, if you have multiple pre-save middleware functions, next will call a function that will call the next pre-save middleware or on error, will pass the error back to your save callback.

Using done is a more advanced option for flow control, allowing multiple pre-save, for example, middleware to execute at once, but not moving past the pre-save step until done has been called in all middleware functions.

like image 152
wprl Avatar answered Sep 20 '22 11:09

wprl