2016-08-30 37 views
0

我已经在节点js中使用填充方法进行引用,但我对填充方法没有更多的了解。在这段代码中,我是从我的子集合中引用用户集合。我有两个集合一个孩子和第二用户我们如何使用节点j使用填充方法引用mongodb

这孩子收集

userId: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User', 
    index: true 
} 

这是用户采集

"firstname":{type:String}, 
    "lastname":{type:String} 

我从URL(http://localhost:8000/v1/childPopulate/:57a4e4e67429b91000e225a5)发送ID和与我存储用户id查询子模式

这是节点js

this.childPopulate = function(req, res, next){ 
    var o_userid = req.params.id; 
    var query = {userId:o_userid}; 

    Child.findOne(query).populate({ 
    path: 'userId', 
    model: 'User', 
    select: 'firstname lastname' 
    }).exec(function(err,userinfo){ 
    if(err){ 
     return next(err); 
    }else{ 
     res.send(userinfo); 
     console.log(userinfo); 
    } 
    }); 
}; 

但是,这显示了在浏览器

{"message":"Cast to ObjectId failed for value \":57a4e4e67429b91000e225a5\" at path \"userId\""} 

回答

0

错误消息此错误表示要传递一个字符串,而不是对象ID。 基本上,mongodb中的默认id不是普通字符串。 它是一个独特的12字节标识符。

所以你应该将字符串转换为ObjectID类型。

var query = {userId: mongoose.Types.ObjectId(stringId)}; 
相关问题