I am trying to remove all Entity related data using Mongoose middlewares.
I am calling entity.remove() and I am removing Contacts, Credentials, Accounts using EntitySchema.pre middleware.
EntitySchema.pre('remove', async function (next) {
this.contacts.forEach(c => Contact.remove({ _id: c._id }).exec());
this.credentials.forEach(c => Credential.remove({ _id: c._id }).exec());
this.accounts.forEach(a => Account.remove({_id: a._id}).exec());
next();
});
Except these I have Ledgers that are related with Accounts with acccountNumber property. I want to remove these Ledgers when Accounts removed with code below.
AccountSchema.pre('remove', async function (next) {
await Ledger.deleteMany({accountNumber: this.accountNumber});
next();
});
But they are not removing. I also put breakpoint to this part of code, it doesn't even passing through this part of code.
How can I deal in this situation?