mongoose 中间件中的 exec() 和 next() 调用在级联删除中的作用是什么?

What is the role of exec() and next() call in cascade delete in mongoose middleware?

我刚开始使用 mongoose 中间件,不知道我是否掌握得很好。这是目的。保存部门后,我想填充大学并将 departmentId 保存在大学对象中。

DepartmentSchema.post('save', function(next) {

  var departmentId = this._id;

  University.findOne({
    _id: this.university
  }, function(err, university) {
    if (!university.departments) {
      university.departments = [];
    }
    university.departments.push(new ObjectId(departmentId));
    university.save(function(err) {
      if (err) return console.log('err-->' + err);
      // saved!
    });
  });

});

这工作正常,但我不确定为什么在 Cascade style delete in Mongoose 他们使用了 exec() 和 next() 调用。你能告诉我这些电话的目的吗?我不知道他们做什么,也找不到相关文档。我只是想确保我没有遗漏任何东西。

clientSchema.pre('remove', function(next) {
  // 'this' is the client being removed. Provide callbacks here if you want
  // to be notified of the calls' result.
  Sweepstakes.remove({
    client_id: this._id
  }).exec();
  Submission.remove({
    client_id: this._id
  }).exec();
  next();
});

Post 中间件没有对下一个函数的引用,你不能做任何流控制。它实际上是通过刚刚保存的部门,所以你的代码可以是这样的:

DepartmentSchema.post('save', function(department) {
  var departmentId = department._id;

pre 中间件中,您可以按执行顺序访问 next 中间件。这是特定钩子上的定义顺序。

// hook two middlewares before the execution of the save method
schema.pre('save', pre1);
schema.pre('save', pre2);
function pre1(next) {
  // next is a reference to pre2 here
  next()
}
function pre2(next) {
  // next will reference the hooked method, in this case its 'save'
  next(new Error('something went wrong');
}
// somewhere else in the code
MyModel.save(function(err, doc) {
 //It'll get an error passed from pre2
});

Mongoose 还使您能够在 parallel 中执行 pre 个中间件,在这种情况下,所有中间件将并行执行,但挂钩方法将不会执行,直到从每个中间件调用完成.

至于 exec() 函数,在 Mongoose 中有两种执行查询的方法,将回调传递给查询或将其与 exec() 链接起来:User.remove(criteria, callback)User.remove(criteria).exec(callback),如果您不将回调传递给查询,它将 return 一个查询对象并且不会执行,除非您将其与 exec()

链接起来