简体   繁体   English

带有ref数组的Mongoose NodeJS Schema

[英]Mongoose NodeJS Schema with array of ref's

I know there is allot's of answers about it but still I didn't quite get the idea. 我知道有相关的答案,但我还是不太明白。 I have CourseSchema : 我有CourseSchema

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

And a StudentSchema : 还有一个StudentSchema

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

I want to reffer enrolledStudents at CourseSchema with a student, and enrolledCourses at StudentSchema with a course. 我想reffer enrolledStudentsCourseSchema与学生和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();
});
});

but when posting I get an error: 但是发布时出现错误:

TypeError: Cannot read property 'enrolledStudents' of null TypeError:无法读取null的属性'enrolledStudents'


Ok so after readying Query-populate I did that: 好了,在准备好查询填充之后,我做到了:

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

And when i'm hitting POST on postman I get on the console: 当我在邮递员上点击POST时,我进入了控制台:

The course name is intro for cs 课程名称是CS的简介

but it is loading for ever and later on console I get: 但是它永远加载,后来在控制台上我得到:

POST /courses/addStudentToCourse - - ms - - POST / courses / addStudentToCourse--ms--

You are missing the populate instruction. 您缺少填充指令。 For example: 例如:

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

  });

It is working by using the ref field that "knows" how to populate withput using the push syntax. 它通过使用ref字段来工作,该ref字段“知道”如何使用push语法填充内容。 it is like a foreign key population. 它就像一个外来人口。

Just call the populate method on the query and an array of documents will be returned in place of the original _ids. 只需在查询上调用populate方法,就会返回文档数组来代替原始_id。 you can learn more on the internals of the populate methods in the official docs 您可以在官方文档中了解有关填充方法的内部知识的更多信息

that is what i did: 那就是我所做的:

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

    });
});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM