【发布时间】:2017-12-13 05:40:10
【问题描述】:
我知道有很多关于它的答案,但我还是不太明白。
我有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'
}]
});
我想将enrolledStudents 转至CourseSchema 与学生联系,并将enrolledCourses 转至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: 无法读取属性 '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 时,我会进入控制台:
课程名称是cs的介绍
但它会永远加载到我得到的控制台上:
POST /courses/addStudentToCourse - - ms - -
【问题讨论】:
-
在您的
const CourseSchema = new ...声明中,尝试将ref: 'Student'更改为ref: 'StudentSchema'。不确定,但可能有效。
标签: node.js mongodb mongoose populate ref