如何删除列表的内容不仅列表?如果x在y中,则在删除x时也删除y

问题描述 投票:1回答:1

我有两个收藏,

  • 教室
  • 学生们

这是他们的架构

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

谢谢!

node.js mongodb express mongoose
1个回答
1
投票

以下代码将有所帮助:

req.params.id应该是课堂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('/');
    }
  })
});
© www.soinside.com 2019 - 2024. All rights reserved.