node.js - 如何在 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
}})
请让我知道删除学生以及学校和课程的正确方法。
解决方案
首先,我会尝试找到学校。这是我想要删除的最后一件事,因为我们需要其中的 ID 和信息。
const school = await schools.findOne({ _id: req.parmas.schoolId })
所以现在我从学校获得了信息,我将继续尝试删除课程。由于学生存储在一个数组中,因此我将不理会这些学生,只专注于删除课程。
Course.remove({ 'students.type': school._id })
.
删除课程后,您应该删除学校。
school.remove()
推荐阅读
- python - 如何使用 Python 中的参数运行 PowerShell 脚本
- java - 选中复选框时,如何使用 e.getStateChanged 获取分配给它的文本?
- pandas - 当因变量的变化非常小时,使用什么指标来定义模型性能?
- python - 合并递归排序的链表未运行
- python - 使用 chart.set_table 设置数字格式
- c++ - 单例模板类同时交换 T 个对象
- go - How to sort a map by two values?
- sql - 将 3 个大表与 2 个连接结合起来
- javascript - 如何通过javascript获得二叉树编码的视觉表示?
- ios - 为 ios 构建 expo 应用程序时出现错误