mongoos pre / save /(串行/并行)中间件绑定了哪些函数完成/下一步
尝试通过文档/博客(Tim Casewell)了解mongoose中间件(前/保存/并行)。
基于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.
什么是/下一步在这里? 你能举一个完整的例子来说明如何使用它吗?
例如:我使用序列如下:
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(); } });
什么是下一个在这里? 它需要绑定到某些东西才能被执行? 我不明白下一个/完成哪个function是指的?
如果你可以详细说明我的代码的控制stream程,这将是一个很大的帮助。
————- 这只是为了阐明我的理解(不是问题的一部分) ——
* 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
它们绑定到在Mongoose内部提供stream控制的函数。 Mongoose依赖于hooks-js的中间件function,请参阅源代码以获取更多详细信息。
例如,如果您有多个预保存中间件函数, next
会调用一个将调用下一个预保存中间件的函数,或者将错误传递回您的save
callback函数。
使用done
是stream程控制的更高级选项,允许多个预先保存的(例如中间件)一次执行,但不会移过预保存步骤,直到在所有中间件function中调用done
为止。