如何删除MongoDB中的多级引用模式



我正在创建一个ERP系统,其中学校有课程,课程包含学生。我想强制API删除一个同时删除课程的学校和所有注册课程的学生。

这就是我在API逻辑中所做的:-

app.delete("/fetchSchool/:schoolId", async (req, res) => {
try {
const deletedSchool = await schools.findByIdAndDelete(req.params.schoolId);
(!deletedSchool) ? res.send('Invalid Request'):
courses.remove({_id: {$in: deletedSchool.course}}, (error, deletedCourse) => {
error ? res.send('Subsequent Deletion Of Course Failed'):
students.remove({_id: {$in: deletedCourse.students}}, (error, response) => {
error ? res.send(error): res.send('Deletion Successfull');
})
})
} catch (error) {
res.status(500).send('some error occured,' + error.message);
}
})

但这只会删除学校和学校课程,但学生数据仍然存在。

这是我的模式:-

学校架构

const SchoolSchema = mongoose.Schema({
course: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'course'
}] 
})

课程架构

const CourseSchema = mongoose.Schema({
students: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'student'
}]
})

学生模式

const StudentSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
unique: true
}})

请让我知道删除学生以及学校和课程的核心方法。

首先,我会设法找到学校。这是我最不想删除的东西,因为我们需要它的ID和信息

const school = await schools.findOne({ _id: req.parmas.schoolId })

所以现在我有了学校的信息,我会继续努力,删除课程。由于学生存储在一个数组中,所以我不去管这些,只专注于删除课程。

CCD_ 2。

删除课程后,您应该删除学校。

school.remove()

解决方案#1

  1. 找到学校。

  2. 通过school.courses.查找课程

  3. 绘制路线图。

  4. 删除许多学生的课程。学生。

  5. 删除课程。

  6. 删除学校。

    app.get("/fetchSchool/:schoolId", async (req, res) => {
    const schoolId = req.params.schoolId;
    try {
    // find one school
    const findSchool = await schools.findOne({ _id: schoolId });
    if (findSchool) {
    // find the courses in the school.courses
    const findCourses = await courses.find({ _id: { $in: findSchool.courses } });
    if (findCourses) {
    // map through courses to get every course
    findCourses.map(async (course) => {
    // find the students in the mapped course AND remove them
    const deleteStudents = await students.deleteMany({ _id: { $in: course.students } })
    if (deleteStudents) {
    // Remove the courses
    const deletedCourses = await courses.deleteMany({ _id: { $in: findSchool.courses } });
    if (deletedCourses) {
    // Remove the school
    const deletedSchool = await schools.deleteOne({ _id: schoolId });
    if (deletedSchool) {
    res.status(200).send('Deleted (school, courses, students) successfully');
    } else { res.send("school not deleted") }
    } else { res.send("courses not deleted") }
    } else { res.send("courses not deleted") }
    })
    } else { res.send("no courses") }
    } else { res.send("no school") }
    } catch (error) {
    res.status(500).send('some error occured, ' + error.message);
    }
    })
    

溶液#2

您可以在Mongoose中使用PrePost钩子,但请确保在模型文件中的Mongoose.model((行之前编写。

最新更新