6

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

1 回答 1

8

They're bound to functions that provide flow control internally within Mongoose. Mongoose depends on hooks-js for its middleware functionality, see the source for more details.

For example, if you have multiple pre-save middleware functions, next will call a function that will call the next pre-save middleware or on error, will pass the error back to your save callback.

Using done is a more advanced option for flow control, allowing multiple pre-save, for example, middleware to execute at once, but not moving past the pre-save step until done has been called in all middleware functions.

于 2013-07-05T16:28:39.593 回答