can't populate the array with mongoose in node.js -


this schema on 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 mongodb, have created existing courses , users, , when user want participate course, user reference added students array in course model.

here how try add user reference 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 above function executed, students array has objectid or reference of user. however, when want populate students course model, 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 problem on populate function, wonder there wrong joincourse function? change 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 populate doesn't work. note, using mongoose 3.6

populate populates model instance, callback passed model instance on call populate, , not 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);   }       }); 

Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -