node.js - 如何在模型中删除程序时自动删除与特定程序相关的所有评论
问题描述
我正在开发一个具有 aprogram model
和 的应用program
程序comments
作为参考。我现在正在努力的是如何在删除时自动删除与comments
特定相关的所有内容。我希望在 中完成此操作,因为我正在使用. 删除将从页面中进行。program
program
model
AdminBro
Admin
Admin
我尝试做这样的事情,但它不工作
这是我的Program model
。
const mongoose = require("mongoose");
const programImageBasePath = "uploads/programImages";
const path = require("path");
require("dotenv").config();
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const programSchema = new mongoose.Schema({
programtype: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
createdAt: {
type: Date,
required: true,
default: Date.now,
},
programImage: {
type: String,
require: true,
},
programcomments: [{ type: Schema.Types.ObjectId, ref: "Programcomment" }],
});
programSchema.pre("remove", function (next) {
Programcomment.remove({ programcomments: this._id }).exec();
next();
});
programSchema.pre("deleteOne", function (next) {
const programId = this.getQuery()["_id"];
mongoose
.model("Programcomment")
.deleteMany({ program: programId }, function (err, result) {
if (err) {
console.log(`[error] ${err}`);
next(err);
} else {
console.log("success");
next();
}
});
});
module.exports = mongoose.model("Program", programSchema);
module.exports.programImageBasePath = programImageBasePath;