skip to Main Content

Not able to delete cascade as Model.remove() fuction is not available in mongoose.
using findByIdAndDelete is not invoking the middleware:

BootcampSchema.pre('remove',async function(next){  //before deleting the doc
    console.log(`courses being removed from bootcamp ${this._id}`);
    await this.model('Course').deleteMany({bootcamp:this._id});
    next();
});

tried different delete methods but can’t delete cascade

2

Answers


  1. Try using findOneAndRemove:

    BootcampSchema.findOneAndRemove({ _id: <id> });
    
    BootcampSchema.pre('findOneAndRemove', ...);
    
    Login or Signup to reply.
  2. This code is from Bootcamp model, I accidentally named it with C capital in Camp so if you named it Bootcamp just replace it in with your naming convention.

    BootCampSchema.pre('deleteOne', { document: true }, async function(next) {
      console.log(`Courses being removed from bootcamp ${this._id}`);
      await this.model('Course').deleteMany({ bootcamp: this._id });
      next();
    });
    

    This code is from bootcamp controler

    exports.deleteBootcamp = asyncHandler(async (req, res, next) => {
      const bootcamp = await Bootcamp.findById(req.params.id);
    
      if (!bootcamp) {
        return next(new ErrorResponse(`Bootcamp with id of ${req.params.id} not found`, 404));
      }
    
      await bootcamp.deleteOne();
      await Course.deleteMany( { bootcamp: bootcamp._id });
    
      res.status(200).json({ 
        success: true, 
        data: {} 
      })
    });
    

    This works perfectly for me, so I hope it’ll work for others as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search