【问题标题】:What is the role of exec() and next() call in cascade delete in mongoose middleware?mongoose中间件级联删除中exec()和next()调用的作用是什么?
【发布时间】:2015-05-15 11:22:45
【问题描述】:

我是使用 mongoose 中间件的新手,不知道我是否很好地遵循它。这是目的。保存部门后,我想填充大学并将部门 ID 保存在大学对象中。

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();
});

【问题讨论】:

    标签: express mongoose mean-stack meanjs


    【解决方案1】:

    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 中间件,在这种情况下,所有中间件将并行执行,但钩子方法在从每个中间件调用 done 之前不会执行。

    至于 exec() 函数,在 Mongoose 中执行查询有两种方法,将回调传递给查询或与 exec() 链接:User.remove(criteria, callback)User.remove(criteria).exec(callback),如果你不这样做' t 将回调传递给查询,它会返回一个查询对象,除非你用 exec() 链接它,否则它不会执行

    【讨论】:

    • 这是一个很好的见解。您在哪里可以找到这些信息?我在官方文档中没有看到这一点。这些东西你是通过跳入源代码学到的吗?
    • 现在当我查看文档时,我在其中找到了这些信息。
    • 谢谢,很高兴它有帮助,因为你现在发现它都在文档中,但是猫鼬文档比它应该的详细一点:)
    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 2015-07-27
    • 2016-01-31
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多