2017-07-09 10 views
0

私はそこに答えがあるのは分かっていますが、それでも私はそのアイデアを得ていません。 私はCourseSchemaを持っている:もちろんで私は学生とCourseSchemaenrolledStudentsをrefferしたいリファレンスが配列されたMongoose NodeJSスキーマ

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

、およびStudentSchemaenrolledCourses

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

StudentSchema

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


[OK]を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 - -

+0

、 'refを変更してみてください。「Student''を'ref: 'StudentSchema''へ。わかりませんが、うまくいくかもしれません。 – oneturkmen

答えて

0

あなたが移入命令が欠落しています。たとえば:

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

    }); 

それはプッシュ構文を使用してwithput移入する方法を「知っている」ということREFフィールドを使用して取り組んでいます。それは外来人口のようなものです。

クエリのpopulateメソッドを呼び出すと、元の_idsの代わりにドキュメントの配列が返されます。あなたは私がやったことです移入法の内部in the official docs

+0

[OK]を、私はプッシュと人口をundrstendしかし、どのように私はspicifice学生を選択するのですか? –

+0

コースには学生の参考文献リストがあります。したがって、学生のrefフィールドにIDを追加すると、自動的にこのコースに関連する学生を記入します。 –

+0

updated私の質問 –

0

に多くを学ぶことができます=新... `宣言あなたの`のconst CourseSchemaで

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

    }); 
}); 
}); 
関連する問題