试图通过 docs/blogs(Tim Casewell) 了解 mongoose 中间件(pre/save/parallel)。
基于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();
}
});
接下来是什么?它需要绑定到某些东西才能执行吗?我不明白 next/done 指的是哪些功能?
如果您可以详细说明我上面的代码的控制流程,那将是一个很大的帮助。
-------------这只是为了阐述我的理解(不是问题的一部分) ------
* 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