[英]How we reference mongodb using populate method using node js
I have doing referencing using the populate method in node js , but I have no more idea about the populate method. 我在使用node js中的populate方法进行引用,但是我对populate方法一无所知。 In this code, i am a reference to user collection from my child collection.
在这段代码中,我引用了我的子收藏夹中的用户收藏夹。 I have two collections one child and second user
我有两个收藏集,一个孩子,另一个用户
This child collection 这个孩子收藏
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
index: true
}
This is user collection 这是用户集合
"firstname":{type:String},
"lastname":{type:String}
I have send id from URL ( http://localhost:8000/v1/childPopulate/:57a4e4e67429b91000e225a5 ) and queried with my stored userId in child schema 我已经从URL( http:// localhost:8000 / v1 / childPopulate /:57a4e4e67429b91000e225a5 )发送了ID,并在子模式中查询了我存储的userId
This is node js 这是节点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);
}
});
};
But this shows this error in browser 但这在浏览器中显示此错误
{"message":"Cast to ObjectId failed for value \":57a4e4e67429b91000e225a5\" at path \"userId\""}
The error message indicates that you are passing a string instead of ObjectID. 该错误信息表明您正在传递字符串而不是ObjectID。 Basically the default id in mongodb is not a normal string.
基本上,mongodb中的默认ID不是普通字符串。 Its is a unique 12-byte identifier.
它是一个唯一的12字节标识符。
So you should convert the string to type ObjectID. 因此,您应该将字符串转换为ObjectID类型。
var query = {userId: mongoose.Types.ObjectId(stringId)};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.