简体   繁体   中英

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

/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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM