Imagine having 4 different models structured like this:
┌────────────┐ ┌────────────┐
│ User │ │ Goal │
├────────────┤ 1 ├────────────┤ 1
│ _id │◄──┐ │ _id │◄──┐
└────────────┘ └──┤ ref_user │ │
1..*└────────────┘ │
│
┌───────────┐ ┌───────────────┐ │
│ Date │ │ Data │ │
├───────────┤ 1 ├───────────────┤ │
│ _id: date │◄─┐ │ _id │ │
└───────────┘ └──┤ ref_date │ │
1 │ ref_goal ├──┘
└───────────────┘ *
The scenario involves a pre remove
operation that automatically deletes associated dates when removing data.
DataSchema.pre('remove', async function (next) {
try {
await DateModel.findByIdAndRemove(this.ref_date);
console.log("Date removed");
next();
} catch (err) {
console.log(err);
next(err);
}
});
An issue arises when deleting a goal, where all associated data should be deleted as well. The expected behavior is that the pre remove
hook in Data should trigger upon removal of data caused by another pre remove
hook. However, this does not occur currently.
Although it is possible to retrieve an array of Data from Goal and individually delete dates, there may be a more efficient approach.
Is there a method to prompt the pre-remove action in Data from the pre-remove event in Goal? Alternatively, is there a way to delete all Dates from an array of Data?
Note: Similar functionality will be required for user deletion in the future (removing goals, then data and dates).
Edit:
Provided below is the pre-remove hook for Goal:
GoalSchema.pre('remove', async function (next) {
try {
await DataModel.deleteMany({ 'ref_goal': this._id });
console.log("Data removed");
next();
} catch (err) {
console.log(err);
next(err);
}
});
Attempts with methods like deleteMany
or remove
have not successfully triggered the pre-remove hook in Data.
Environment:
"express": "^4.17.1",
"mongoose": "^5.12.2",