我有两个收藏,
这是他们的架构
**CLASSROOM SCHEMA**
const mongoose = require('mongoose');
const classroomSchema = new mongoose.Schema({
classroomname: {
type: String
},
createdAt: { type: Date, default: Date.now },
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
students: {
id : {
type: mongoose.Schema.Types.ObjectId,
ref: "Student"
}
}
});
const Classroom = mongoose.model('Classroom', classroomSchema);
module.exports = Classroom;
和..
**STUDENT SCHEMA**
const mongoose = require('mongoose');
const studentSchema = new mongoose.Schema({
fullName: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
},
classroom: {
name: {
type: String
},
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "classroom",
}
},
});
const Student = mongoose.model('Student', studentSchema);
module.exports = Student;
这就是学生的样子
- 其中author.id是登录后创建该学生的user.id英寸。
我有以下代码可以成功删除学生
router.get('/delete/:id',passportConfig.isAuthenticated,(req, res) => {
Student.findByIdAndRemove(req.params.id, (err, docs) => {
if (!err) {
res.redirect('/');
}
else {console.log('Error in classroom deletion:' +err);}
});
});
..以及用于删除教室的非常相似的代码。我的问题是,当我删除一个教室时,如何同时删除属于该教室的所有学生?
这是我的逻辑
find classroom id
find student.classroom.id
if student.classroom.id == classroom.id
Classroom, Student findbyid and remove
谢谢!
下面的代码会有帮助:
req.params.id should be classroom id.
router.get('/delete/:id',passportConfig.isAuthenticated,(req, res) => {
// To Delete Classroom by id
Classroom.remove({_id : mongoose.Schema.Types.ObjectId(req.params.id)}, (errClass, classroomRes) => {
if (!errClass) {
console.log('Classroom Removed :',classroomRes);
// delete stud which has classroom Id.
Student.remove({'classroom.id' : mongoose.Schema.Types.ObjectId(req.params.id)}, (errStud, studentRes) => {
if(!errStud){
console.log('studentRes Removed :',studentRes);
}else{
console.log('Error in Student deletion:',errStud);
}
return res.redirect('/');
});
}else{
console.log('Error in Classroom deletion:',errClass);
return res.redirect('/');
}
})
});
我是一名优秀的程序员,十分优秀!