#node.js #mongodb #express #mongoose
#node.js #mongodb #выразить #мангуст
Вопрос:
У меня есть две коллекции,
- Классы
- Для студентов
Вот их схема
**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
Спасибо!
Ответ №1:
Приведенный ниже код поможет :
req.params.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('/');
}
})
});
Комментарии:
1. работает как шарм, единственное изменение, которое требовалось, было: «мангуст. Типы. ObjectId» вместо mongoose. Схема. Типы. ObjectId. Спасибо!