Revinda Kumara
Revinda Kumara

Reputation: 25

mongoose pre function doesn't work on middle ware remove

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

Answers (2)

robertklep
robertklep

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 call myDoc.remove(), not when you call MyModel.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

Shubham
Shubham

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

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

Upvotes: 0

Related Questions