【发布时间】:2017-01-08 15:22:04
【问题描述】:
我有以下架构
var Topic= new Schema({
text: String,
topicId: String,
comments: [{type: Schema.Types.ObjectId, ref:'Comment'}]
});
var Comment = new Schema({
text: String
});
我正在编写 RESTFul API,它将根据主题 ID 和评论 ID 为我提供评论详细信息
/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"
}
}
这里有什么问题以及如何解决?有没有更好的方法来查询所需的对象?
【问题讨论】:
标签: javascript node.js mongodb express mongoose