Automatically remove referencing objects on deletion in MongoDB

PHOTO EMBED

Fri Jan 08 2021 09:47:06 GMT+0000 (Coordinated Universal Time)

Saved by @ali_alaraby

RoleModel.pre('deleteOne', async function(next) {

    try {
        let deletedItemId = (this._conditions && this._conditions._id) ? this._conditions._id : null;
        if(deletedItemId){
            await UserModel.deleteMany({ 'role': deletedItemId });
        }
        next();
    } catch (e) {
        console.log(e);
    }
});
content_copyCOPY