【问题标题】:can't populate the array with mongoose in node.js无法在 node.js 中用猫鼬填充数组
【发布时间】:2013-03-31 01:51:32
【问题描述】:

这是我在课程中的架构

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

在mongodb中,我已经创建了已有的课程和用户,当用户想参加课程时,用户引用会被添加到课程模型中的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);
        }
    })

} 

执行上述函数时,students 数组中有用户的objectID 或reference。但是,当我想从课程模型中填充学生时,它不起作用。

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

我没有发现 populate 函数有任何问题,所以我想知道 joinCourse 函数有什么问题吗?所以我将函数更改为

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

                });
            }
   })  

但填充仍然不起作用。注意,我使用的是猫鼬 3.6

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    populate 填充模型实例,但回调传递的是您调用填充的模型实例,而不是填充的数据本身:

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

    【讨论】:

    • 真的,效果很好,我没想到这是问题所在,非常感谢罗伯特
    猜你喜欢
    • 2019-09-16
    • 2020-01-30
    • 2014-04-19
    • 1970-01-01
    • 2015-07-13
    • 2015-11-24
    • 2021-08-16
    • 2020-11-02
    相关资源
    最近更新 更多