Reputation: 25
I have tries to delete referenced documents in mongoDb when Company is deleting.But after i execute following it only deletes the Company and not executing middle ware body
const removedCompany = await CompanyModel.findOne({ _id: id }).remove();
inside schema file
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();
});
Upvotes: 0
Views: 762
Reputation: 203359
As per 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 callmyDoc.remove()
, not when you callMyModel.remove()
.
If you rewrite your query to use findOneAndRemove
, you can add a middleware/hook for that.
Also take into account Shubham's answer regarding arrow function expressions.
Upvotes: 1
Reputation: 1426
lambda function implements "this" as lexical this so it will not work use old style
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();
});
Upvotes: 0