[英]Mongoose: CastError on querying incorrect ObjectId for nested object
I have following schema 我有以下架构
var Topic= new Schema({
text: String,
topicId: String,
comments: [{type: Schema.Types.ObjectId, ref:'Comment'}]
});
var Comment = new Schema({
text: String
});
I am writing RESTFul API that will give me the Comment details as per topic ID and Comment ID 我正在编写RESTFul API,它将根据主题ID和评论ID为我提供评论详细信息
/topics/{id}/comments/{id}
Following is the function that gets data from Mongo 以下是从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]);
});
}
The code works fine if I specify the right comment ID, but if I specify non-existing comment ID in URL then I get following error 如果我指定了正确的注释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"
}
}
What is the issue here and how to fix it?? 这里有什么问题以及如何解决? Is there better way to query the required object? 有没有更好的方法来查询所需的对象?
The issue isn't that your specifying a non-existing comment ID. 问题不是您指定的注释ID不存在。 It's that you're specifying a string that can't be converted into a valid ObjectId. 这是因为您指定的字符串无法转换为有效的ObjectId。 Your test string, "57c738b66d790f0c1bdb179" is a 23 character hex string. 您的测试字符串“ 57c738b66d790f0c1bdb179”是一个23个字符的十六进制字符串。 It should be length 24. 长度应为24。
If you want to validate before attempting your query, there are several different ways you could go about it. 如果要在尝试查询之前进行验证,可以采用几种不同的方法。 Here's one example: Can I determine if a string is a MongoDB ObjectID? 这是一个示例: 是否可以确定字符串是否为MongoDB ObjectID?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.