我试图通过文档和博客(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.
这里的“done/next”是什么意思?您能否给出一个完整的使用示例,以便更加易于理解?例如:我使用串行通信如下所示:
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