Node.js 带有ref';s

Node.js 带有ref';s,node.js,mongodb,mongoose,populate,ref,Node.js,Mongodb,Mongoose,Populate,Ref,我知道关于这个问题有很多答案,但我还是不太明白。 我有CourseSchema: const CourseSchema = new Schema({ course_name: String, course_number: {type: String, unique : true }, enrolledStudents:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Student' }] }); const StudentSchem

我知道关于这个问题有很多答案,但我还是不太明白。 我有
CourseSchema

const CourseSchema = new Schema({
course_name: String,
course_number: {type: String, unique : true },
enrolledStudents:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student' }]
});
const StudentSchema = new Schema({
first_name: String,
last_name: String,
enrolledCourses:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CourseSchema'
    }]
});
学生模式

const CourseSchema = new Schema({
course_name: String,
course_number: {type: String, unique : true },
enrolledStudents:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Student' }]
});
const StudentSchema = new Schema({
first_name: String,
last_name: String,
enrolledCourses:[{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'CourseSchema'
    }]
});
我想在
CourseSchema
与学生一起参考
Enrolled Students
,在
StudentSchema
与课程一起参考
Enrolled Courses

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:无法读取null的属性“Enrolled Students”


好的,在准备好之后,我做到了:

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);
    });
});
当我在《邮差》上发表文章时,我会在控制台上:

课程名称为cs简介

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

发布/课程/添加学生至课程——ms--


您缺少填充指令。例如:

它通过使用ref字段来工作,ref字段“知道”如何使用push语法填充withput。它就像一个外键人口

只需在查询中调用populate方法,就会返回一个文档数组来代替原始的_id。您可以了解有关填充方法内部的更多信息,这就是我所做的:

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");
                }
            });
        });

    });
});
});

在您的
const CourseSchema=new…
声明中,尝试将
ref:'Student'
更改为
ref:'StudentSchema'
。不确定,但可能有效。好的,我会取消推送并填充,但我如何选择spicifice学生?本课程有一个学生参考列表。因此,如果您在学生的ref字段添加id,那么它将自动为您填充本课程的相关学生。