What functions are executed / followed in mongoos pre / save / (serial / parallel) middleware

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 
+6
source share
1 answer

They are connected by functions that provide flow control inside Mongoose. Mongoose is dependent on hooks-js for its middleware functionality. See the source for more details.

For example, if you have several predefined middlewares, next will call a function that will call the next preliminary save of the middleware, or if it fails, it will pass the error back to your save callback.

Using done is a more advanced flow control option that allows you to simultaneously perform multiple presets, such as middleware, but do not move after the pre-save step until done is called in all the middleware functions.

+8
source

Source: https://habr.com/ru/post/948647/


All Articles