猫鼬前置功能不适用于中间件删除

mongoose pre function doesn't work on middle ware remove

当公司为 deleting.But 时,我尝试删除 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();
});

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

根据the documentation

Note: There is no query hook for remove(), only for documents. If you set a 'remove' hook, it will be fired when you call myDoc.remove(), not when you call MyModel.remove().

如果您重写查询以使用 findOneAndRemove,您可以为此添加一个 middleware/hook。

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