0
ため、誤ったObjectIdを照会に私は次のしているスキーママングース:CastErrorネストされたオブジェクト
var Topic= new Schema({
text: String,
topicId: String,
comments: [{type: Schema.Types.ObjectId, ref:'Comment'}]
});
var Comment = new Schema({
text: String
});
私はID私のトピックIDごとなどのコメントの詳細を与えるとコメントますRESTfulなAPIを書いています
/topics/{id}/comments/{id}
以下は、Mongoからデータを取得する関数です。
getCommentsById: function(req, resp){
req.db.Topic.findOne({"topicId": req.params.topicId})
.populate({path:"Comments", match:{"_id": req.params.commentId}})
.exec(function(err, topic){
if(err) {
return resp.status(500).json({
message: 'Error when getting Topic.',
error: err
});
}
if (!topic) {
return resp.status(404).json({
message: 'No such Topic'
});
}
if (!topic.comments || topic.comments.length==0) {
return resp.status(404).json({
message: 'No such Comment'
});
}
resp.json(topic.comments[0]);
});
}
コメントID右が、私はURLに存在しないコメントIDを指定した場合、私は
{
"message": "Error when getting Topic.",
"error": {
"message": "Cast to ObjectId failed for value \"57c738b66d790f0c1bdb179\" at path \"_id\"",
"name": "CastError",
"kind": "ObjectId",
"value": "57c738b66d790f0c1bdb179",
"path": "_id"
}
}
エラーを以下の取得ここでの問題とどのようにそれを修正するにはどうです?必要なオブジェクトをクエリするより良い方法はありますか?
ありがとうございます。答えはすでに受け入れられていますが、上記のコードがネストされたレコードを取得する正しい方法であるかどうか教えてください。 – sidgate
それは私にはうまく見えますが、私はマングースを使わないので、私は聞くのに最適な人ではありません。ネイティブのmongodbを使用すると、$ lookupを使うか、2番目のクエリを使って子データを取得するだけです。 – Wake