mongoose的pre/save/(serial/parallel)中间件绑定了哪些函数?

6

我试图通过文档和博客(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
1个回答

8

它们绑定到在Mongoose内部提供流程控制的函数上。Mongoose依赖于hooks-js来实现中间件功能,请查看源代码以获取更多详细信息。

例如,如果您有多个pre-save中间件函数,next将调用一个函数,该函数将调用下一个pre-save中间件或在错误时将错误传递回您的save回调函数。

使用done是一种更高级的流程控制选项,允许多个pre-save中间件同时执行,但在所有中间件函数中调用done之前不会超过pre-save步骤。


感谢您的回复,根据您提供的关键词,我找到了 https://github.com/bnoguchi/hooks-js 这个项目,解决了很多问题。我会尽快接受您的答案。 - GJain
啊,很酷。我没有意识到mongoose使用了中间件的依赖。这实际上非常方便。 - wprl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接