给出了两个猫鼬模型,该模型的一个字段带有嵌入式文档,由ObjectId引用:
//Student.js
module.exports = new Schema({
name: {
type: String,
required: true
},
documentId: {
type: String,
required: true,
unique: true
},
courses: [
{
type: ObjectId,
ref: 'Courses',
required: true
}
]})
//Course.js
module.exports = new Schema({
name: {
type: String,
required: true
},
students: [
{
type: ObjectId,
ref: 'Students'
}
]})
我要在删除Student后立即从Course.students数组中删除给定的Student ObjectId。为此,我对此进行了编码:
removeStudent(documentId) {
return Promise.resolve()
.then(() => {
return Students.findOne({ documentId })
})
.then(student => {
if (!student) throw Error('student does not exist')
const coursesToBePulled = student.courses.toString().split(',')
const studentMongoId = student._id.toString()
async function updateStudentInCourses (coursesToBePulled, studentMongoId) {
for (const item in coursesToBePulled) {
await Courses.findByIdAndUpdate(coursesToBePulled[item], { $pull: {'students': studentMongoId}}, {'new': true})
}
return Students.deleteOne({ documentId })
}
return updateStudentInCourses (coursesToBePulled, studentMongoId)
})
}
问题是当我在循环内使用findByIdAndUpdate-$ pull时,它仅在第一次迭代中能正常工作。对于其他迭代,不拉取引用的ID,而是将空值设置为Courses.students数组。删除学生后,我将获得此文档:
{
"_id" : ObjectId("5c4443f45c8c1d110671f7ed"),
"students" : [
null
],
"name" : "curs 2",
"__v" : 0
}
回顾一下,如果一个学生在3门课程中被引用,当我删除该学生时,只会在第一次迭代中将其从Courses.students中删除,而在另外2次迭代中,它将在Courses.students中放置一个空值。
如何使它正常工作。
非常感谢!