【问题标题】:which functions done/next are bound to in mongoos pre/save/(serial/parallel) middleware在 mongoose pre/save/(serial/parallel) 中间件中绑定了哪些函数 done/next
【发布时间】:2013-07-06 10:04:56
【问题描述】:

试图通过 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

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    它们绑定到在 Mongoose 内部提供流量控制的函数。 Mongoose 的中间件功能依赖于 hooks-js,详情请参阅源代码。

    例如,如果您有多个预保存中间件函数,next 将调用一个函数,该函数将调用下一个预保存中间件或出错时,会将错误传递回您的 save 回调。

    使用done 是一种更高级的流控制选项,允许同时执行多个预保存,例如中间件,但在所有中间件中调用done 之前不会超过预保存步骤功能。

    【讨论】:

    • 谢谢。根据您回复中的一些关键字,我能够找到github.com/bnoguchi/hooks-js,它清除了很多东西。我会尽快接受你的回答。
    • 啊,酷。我没有意识到 mongoose 使用了中间件的依赖项。这实际上非常方便。
    猜你喜欢
    • 2017-01-31
    • 1970-01-01
    • 2012-10-19
    • 2018-11-17
    • 1970-01-01
    • 2021-01-08
    • 2015-07-20
    • 2018-04-22
    • 2017-10-25
    相关资源
    最近更新 更多