中间件

中间件(也称为前后挂钩)是在执行异步功能期间传递控制的函数。中间件在架构级别指定,对编写插件很有用。Mongoose 4.0 有两种类型的中间件:文件中间件和查询中间件。以下文档功能支持文档中间件。

  • 在里面
  • 验证
  • 保存
  • 去掉

以下模型和查询功能支持查询中间件。

  • 计数
  • 找一个
  • findOneAndRemove
  • findOneAndUpdate
  • 更新

文档中间件和查询中间件都支持前后挂钩。

有两种类型的预钩,串行和并行。

串行

当每个中间件调用 next 时,串行中间件一个接一个地执行。

var schema = new Schema(..);
schema.pre('save', function(next) {
  // do stuff
  next();
});

平行

并行中间件提供更细粒度的流程控制。

var schema = new Schema(..);

// `true` means this is a parallel middleware. You **must** specify `true`
// as the second parameter if you want to use parallel middleware.
schema.pre('save', true, function(next, done) {
  // calling next kicks off the next middleware in parallel
  next();
  setTimeout(done, 100);
});

钩子方法(在本例中为 save)在每个中间件调用完成之前不会执行。

发布中间件

post 中间件在 hooked 方法之后执行,并且所有的预中间件都已完成。post 中间件不直接接收流控制,例如没有传递下一个或完成的回调。post hooks 是一种为这些方法注册传统事件侦听器的方法。

schema.post('init', function(doc) {
  console.log('%s has been initialized from the db', doc._id);
});
schema.post('validate', function(doc) {
  console.log('%s has been validated (but not saved yet)', doc._id);
});
schema.post('save', function(doc) {
  console.log('%s has been saved', doc._id);
});
schema.post('remove', function(doc) {
  console.log('%s has been removed', doc._id);
});