简体   繁体   中英

Pre remove hook - Mongoose

Right now I have an item, and when I remove the item, it triggers the pre 'remove' hook to remove an option group.

item.remove();
itemSchema.pre('remove', async () => {
  await OptionGroup.find({ _id: { $in: this.optionGroups } })
    .remove()
    .exec();
});

The option group has a pre 'remove' hook to remove the options that is referenced by the option group.

optionGroupSchema.pre('remove', async () => {
  await Item.updateMany(
    { optionGroups: this._id },
    { $pull: { optionGroups: this._id } }
  ).exec();
  await Option.find({ _id: { $in: this.options } })
    .remove()
    .exec();
});

I expected a waterfall effect but instead, only the option group is removed. There are other caveats that I do not understand, such as using find to remove is fine, but I cannot directly use remove or deleteMany like this:

itemSchema.pre('remove', async () => {
  await OptionGroup.remove({ _id: { $in: this.optionGroups } })
    .exec();
});

I know from the docs that I can only trigger a pre 'remove' hook when removing document, but in the hook, why I cannot use remove to trigger other pre 'remove' hooks?

So I think for me to understand, I need to know:

  1. How to trigger a waterfall effect where one remove (document) will trigger the remove of others?
  2. When to use deleteMany vs remove?
  3. Does deleteOne or deleteMany trigger the pre 'remove' hook?

Does deleteOne or deleteMany trigger the pre 'remove' hook?

It won't trigger remove hook, you need to use this syntax instead.

schema.post(/Many$/, function(res) {
  console.log('this fired after you ran `updateMany()` or `deleteMany()`);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM