因此,我试图一次删除许多文档,并且出于某种原因,后置中间件适用于
document.deleteOne()
,但不适用于 Model.deleteMany()
。具体来说,我正在寻找一个修复方法,以解决它不会针对 Lecture.deleteMany(...)
和 Chapter.deleteMany(...)
触发的问题。请注意,文档本身最终会被删除。
这是我的一条路线的响应处理程序:
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();
});
这是我的章节模型文件中的后期中间件(与讲座非常相似):
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();
}
);
我想通了。我相信 post 是一个文档中间件,并且由于
Model.deleteMany()
是一个查询,因此不会调用中间件。我更改了下面的代码。
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();
});