Reputation: 8056
This is my schema on the course
var CourseSchema = mongoose.Schema({
students:[{ type: ObjectId, ref: 'User' }]
});
var CourseModel = mongoose.model('Course',CourseSchema);
var UserSchema = mongoose.Schema({ name:String})
var UserModel = mongoose.model('User',UserSchema);
In the mongodb, I have created the existing courses and users, and when the user want to participate the course, the user reference will be added to the students array in the course model.
Here is how I try to add the user reference to the students
function joinCourse(cid,uid,callback){
var options = { new: false };
var uid = mongoose.Types.ObjectId(uid);
CourseModel.findOneAndUpdate({'_id':cid},{'$addToSet':{'students':uid}},options,function(err,ref){
if(err) {
console.log('update joinCourse'.red,err);
callback(err, null);
}else{
console.log('update joinCourse '.green+ref);
callback(null,ref);
}
})
}
when the above function is executed, the students array has the objectID or reference of the user. However, when I want to populate the students from the course model, it doesn't work.
var id = mongoose.Types.ObjectId(id);
CourseModel.findById(id).populate('students').exec(function(err, users) {
if(err){callback(err, null);}
else{
//// users.length == undefined
console.log("findCourseStudentsById".green,users.length);
callback(null, users);
}
})
I didn't find any problem on populate function, so I wonder is there something wrong with joinCourse function? so I change the function as
courseModel.findCourseById(cid,function(err,course){
if(err) next(err);
else{
course.students.push({'_id': mongoose.Types.ObjectId(uid)});
course.save(function (err) {
if (err) next(err);
});
}
})
but still the populate doesn't work. Note, I am using mongoose 3.6
Upvotes: 0
Views: 1683
Reputation: 203231
populate
populates the model instance, but the callback is passed the model instance on which you call populate, and not the populated data itself:
CourseModel.findById(id).populate('students').exec(function(err, course) {
if(err){callback(err, null);}
else{
console.log("findCourseStudentsById".green, course.students.length);
callback(null, course);
}
});
Upvotes: 2