【问题标题】:mongoose pre function doesn't work on middle ware removemongoose pre 功能在中间件移除时不起作用
【发布时间】:2017-08-30 15:07:32
【问题描述】:

在删除公司时,我尝试删除 mongoDb 中的引用文档。但是在我执行之后,它只会删除公司而不执行中间件主体

const removedCompany = await CompanyModel.findOne({ _id: id }).remove();

内部架构文件

CompanySchema.pre('remove', (next) => {
  // 'this' is the company being removed. Provide callbacks here if you want
  // to be notified of the calls' result.
  UserCompany.remove({ companyId: this._id }).exec();
  next();
});

【问题讨论】:

    标签: node.js mongodb mongoose serverless-framework


    【解决方案1】:

    根据the documentation

    注意remove() 没有查询挂钩,仅适用于文档。如果你设置了一个'remove'钩子,它会在你调用myDoc.remove()时被触发,而不是在你调用MyModel.remove()时。

    如果您重写查询以使用findOneAndRemove,您可以为此添加一个中间件/挂钩。

    还要考虑 Shubham 关于箭头函数表达式的回答。

    【讨论】:

      【解决方案2】:

      lambda 函数将 "this" 实现为词法 this 所以它不会工作 使用旧样式

      CompanySchema.pre('remove', function(next){
       // 'this' is the company being removed. Provide callbacks here if you want
       // to be notified of the calls' result.
       UserCompany.remove({ companyId: this._id }).exec();
       next();
      });
      

      https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md#not-just-shorter-syntax-but-this

      【讨论】:

        猜你喜欢
        • 2019-10-27
        • 1970-01-01
        • 1970-01-01
        • 2023-03-17
        • 2019-06-20
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多