2016-08-30 2 views
0

ノードjsのpopulateメソッドを使用して参照を行っていますが、populateメソッドについてはこれ以上考えません。このコードでは、私は私の子コレクションからのユーザーコレクションへの参照です。私は、これはユーザーコレクションノードjsを使用してpopulateメソッドを使用してmongodbを参照する方法

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

ある2つのコレクション1子と第二のユーザ

この子コレクション

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

を持っている私は、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); 
    } 
    }); 
}; 

しかし、これは、エラーメッセージがあなたの代わりにオブジェクトIDの文字列を渡していることを示している

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

答えて

0

ブラウザにこのエラーが表示されます。 基本的に、mongodbのデフォルトのIDは通常の文字列ではありません。 これは、12バイトの一意の識別子です。

文字列をObjectIDに変換する必要があります。

var query = {userId: mongoose.Types.ObjectId(stringId)}; 
関連する問題