Reputation: 15234
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
/topics/{id}/comments/{id}
Following is the function that gets data from 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
{
"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?
Upvotes: 0
Views: 345
Reputation: 1696
The issue isn't that your specifying a non-existing comment ID. It's that you're specifying a string that can't be converted into a valid ObjectId. Your test string, "57c738b66d790f0c1bdb179" is a 23 character hex string. It should be length 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?
Upvotes: 1