gpt4 book ai didi

node.js - 如何删除列表的内容而不仅仅是列表?如果x在y中,则删除x时也删除y

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:40 24 4
gpt4 key购买 nike

我有两个收藏,

  • 教室
  • 学生

这是他们的架构

**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;

这就是学生的样子 enter image description here

  • 其中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('/');
}
})
});

关于node.js - 如何删除列表的内容而不仅仅是列表?如果x在y中,则删除x时也删除y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55819888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com