If I understood you correctly, you can use mongoose middlewares to "cascade deleting". So when a category is removed, you can to code that every product has now "Uncategorized"
You can use a pre
hook when you call delete function and do something like this (not tested with your schema):
category.pre(/(?:delete|remove)/, function(next) {
var id = this.getQuery()._id; //get category _id
product.updateMany({
category: id
},{
$set:{
category:yourUncategorizedId
}
}).then(next()).catch(e => next(e))
})
So, in this case, a regex
match is used to go into the hook.
This hook is called when a remove
or delete
function is called from category
model. So, when a category is deleted, this hook will update all references by your uncategorizedId
to ensure any product has a non-existing category
reference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…