首页 > 解决方案 > 如何在 Mongo-DB 中删除多级引用模式

问题描述

我正在创建一个 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
}})

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

标签: node.jsmongodbapiexpressmongoose

解决方案


首先,我会尝试找到学校。这是我想要删除的最后一件事,因为我们需要其中的 ID 和信息。

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

所以现在我从学校获得了信息,我将继续尝试删除课程。由于学生存储在一个数组中,因此我将不理会这些学生,只专注于删除课程。

Course.remove({ 'students.type': school._id }).

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

school.remove()


推荐阅读