带有引用数组的 Mongoose NodeJS 模式

Mongoose NodeJS Schema with array of ref's

我知道有很多关于它的答案,但我还是不太明白。 我有 CourseSchema:

const CourseSchema = new Schema({
course_name: String,
course_number: {type: String, unique : true },
enrolledStudents:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student' }]
});

还有一个StudentSchema:

const StudentSchema = new Schema({
first_name: String,
last_name: String,
enrolledCourses:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CourseSchema'
    }]
});

我想在 CourseSchemaenrolledStudents 推荐一名学生,并在 enrolledCoursesStudentSchema 推荐一门课程。

router.post('/addStudentToCourse', function (req, res) {
Course.findById(req.params.courseId, function(err, course){
    course.enrolledStudents.push(Student.findById(req.params.studentId, function(error, student){
        student.enrolledCourses.push(course).save();
    })).save();
});
});

但是发帖时出现错误:

TypeError: Cannot read property 'enrolledStudents' of null


好的,准备好后 Query-populate 我做到了:

router.post('/addStudentToCourse', function (req, res) {

    Course.
    findOne({ _id : req.body.courseId }).
    populate({
        path: 'enrolledStudents'
        , match: { _id : req.body.studentId }
    }).
    exec(function (err, course) {
        if (err) return handleError(err);
        console.log('The course name is %s', course.course_name);
    });
});

当我在邮递员上点击 POST 时,我进入了控制台:

The course name is intro for cs

但它一直在加载,稍后在控制台上我得到:

POST /courses/addStudentToCourse - - ms - -

您缺少填充说明。例如:

see more about it here

Course.
  findOne({ courseId : req.params.courseId }).
  populate('enrolledStudents').
  exec(function (err, course) {
    if (err) return handleError(err);
    console.log('The course name is %s', course.name);

  });

它通过使用 ref 字段来工作,"knows" 如何使用推送语法填充输入。好像是外国重点人群

只需在查询中调用 populate 方法,就会返回一个文档数组来代替原始 _id。您可以了解更多关于填充方法的内部结构 in the official docs

我就是这么做的:

router.post('/addStudentToCourse', function (req, res) {
Student.findById(req.body.studentId, function(err, student){
    if(err) return next(err);
    Course.findById(req.body.courseId, function(err, course){
        if(err) return console.log(err);
        course.enrolledStudents.push(student);
        course.save(function (err) {
            if(err)
                console.log(err);
            student.enrolledCourses.push(course);
            student.save(function (err) {
                if (err)
                    console.log(err);
                else{
                    res.send("worked");
                }
            });
        });

    });
});
});