0

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?

sidgate
  • 14,650
  • 11
  • 68
  • 119

1 Answers1

1

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?

Community
  • 1
  • 1
Wake
  • 1,686
  • 10
  • 14
  • Thanks. Though answer is already accepted, can you please tell me if above code is right way to fetch the nested record? – sidgate Aug 31 '16 at 22:37
  • It looks right to me, but I don't use mongoose, so I'm not the best one to ask. Using native mongodb, I'd just use $lookup or simply retrieve the child data using a second query. – Wake Aug 31 '16 at 22:48