在猫鼬文档中,它说“Model.deleteOne() 不会触发 pre('remove') 或 post('remove') 钩子。”
如果您可以使用findByIdAndDelete重构删除操作,则有解决方案,它会触发findOneAndDelete
中间件,
所以我们可以将这个中间件添加到 Project Schema 中。
项目型号:
const mongoose = require("mongoose");
const ProjectChild = require("./projectChild");
const ProjectSchema = new mongoose.Schema({
name: String
});
ProjectSchema.post("findOneAndDelete", async function(doc) {
console.log(doc);
if (doc) {
const deleteResult = await ProjectChild.deleteMany({
parentProject: doc._id
});
console.log("Child delete result: ", deleteResult);
}
});
module.exports = mongoose.model("Project", ProjectSchema);
项目儿童模型:
const mongoose = require("mongoose");
const projectChildSchema = new mongoose.Schema({
name: String,
parentProject: {
type: mongoose.Schema.Types.ObjectId,
ref: "Project"
}
});
module.exports = mongoose.model("ProjectChild", projectChildSchema);
我创建了一个这样的项目:
{
"_id": "5dea699cb10c442260245abf",
"name": "Project 1",
"__v": 0
}
并为此项目创建了 2 个子项目:
孩子 1
{
"_id": "5dea69c7b10c442260245ac0",
"name": "Child 1 (project 1)",
"parentProject": "5dea699cb10c442260245abf",
"__v": 0
}
孩子 2
{
"_id": "5dea69e8b10c442260245ac1",
"name": "Child 2 (project 1)",
"parentProject": "5dea699cb10c442260245abf",
"__v": 0
}
我创建了一个示例路由来通过它的 id 删除一个项目,如下所示:
router.delete("/project/:id", async (req, res) => {
const result = await Project.findByIdAndDelete(req.params.id);
res.send(result);
});
当我向此路由发送 DELETE 请求时,我们会在控制台中看到以下信息:
console.log(doc);
{ _id: 5dea699cb10c442260245abf, name: 'Project 1', __v: 0 }
console.log("Child delete result: ", deleteResult);
Child delete result: { n: 2, ok: 1, deletedCount: 2 }
因此,当我们删除项目时,我们可以删除项目的 2 个子项。
作为替代方案,您也可以使用findOneAndRemove,它会触发 findOneAndRemove 后中间件。
所以在 ProjectSchema 中,我们像这样替换 post 中间件:
ProjectSchema.post("findOneAndRemove", async function(doc) {
console.log(doc);
if (doc) {
const deleteResult = await ProjectChild.deleteMany({
parentProject: doc._id
});
console.log("Child delete result: ", deleteResult);
}
});
当我们使用 findOneAndRemove 操作时,结果将与第一种选择相同:
const result = await Project.findOneAndRemove({ _id: req.params.id });