Search code examples
mongodbmongoosenext.js13

post deleteMany/deleteOne middleware not being called mongoose


So, I'm trying to delete many documents at once, and for some reason, the post middleware works for document.deleteOne(), but not for Model.deleteMany(). Specifically, I am looking for a fix for it not firing for Lecture.deleteMany(...) and Chapter.deleteMany(...). Note that the documents themselves do end up being deleted.

Here is the response handler for one of my routes:

export const DELETE = catchAsync(async function (req, { params }) {
  // Check if course exists
  const course = await Course.findById(params.id).populate({
    path: "chapters",
    select: { id: 1 },
  });
  if (!course)
    return new AppError("No courses found with the provided id", 404);

  const { chapters } = course;
  const chapterIds = chapters.map((chapter) => chapter.id);

  // Delete course's lectures
  await Lecture.deleteMany({ chapter: { $in: chapterIds } });

  // Delete course's chapters
  await Chapter.deleteMany({ _id: { $in: chapterIds } }); // Specifically this one

  // Delete course
  await course.deleteOne();
});

And here is the post middleware in my chapter model file (very similar to lecture):

chapterSchema.post(
  ["deleteOne", "deleteMany"],
  { document: true },
  async function (doc, next) {
    console.log("POST DELETE ONE CHAPTER");

    const course = await Course.findById(this.course);

    // Find and remove chapter from course
    const index = course.chapters.findIndex((ch) => ch._id === doc._id);
    course.chapters.splice(index, 1);
    await course.save();

    next();
  }
);

Solution

  • I figured it out. I believe post is a document middleware, and since Model.deleteMany() is a query, the middleware does not get called. I changed my code the one below.

    chapterSchema.post("deleteOne", { document: true }, async function (doc, next) {
      console.log("Removing chapter from its course");
    
      // Find course
      const course = await Course.findById(doc.course);
      if (!course) return next();
    
      // Find and remove chapter from course
      const index = course.chapters.findIndex((ch) => ch._id === doc._id);
      course.chapters.splice(index, 1);
      await course.save();
    
      next();
    });