我有以下架构
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"
}
}
这里有什么问题以及如何解决?有没有更好的方法来查询所需的对象?
答案 0 :(得分:1)
问题不在于您指定不存在的评论ID。您指定的字符串无法转换为有效的ObjectId。你的测试字符串" 57c738b66d790f0c1bdb179"是23个字符的十六进制字符串。它应该是24长。
如果您想在尝试查询之前进行验证,可以通过几种不同的方式进行查询。这是一个例子:Can I determine if a string is a MongoDB ObjectID?