Trying to understand Mongoose middleware (pre / save / parallel) through 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 being done / next connected here? Could you give a complete example of how to use it?
For example, I use a serial interface 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 connected here? Should it be related to something that needs to be done? I donβt understand which function (s) next / done refer to?
If you could develop a control flow for my code above, that would be a big help.
------------- This is just to clarify my understanding (not a 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
Gjain source share