Search for id Mongo

1

Hello everyone, I'm following the Getting Mean book but I came across a problem I can not solve. I have a document that I show below collecting data from Mongo, and in it I have subdocuments in the case reviews where I want to get the id.
My problem is that I can not return the subdocument with the id. It returns always empty. I need help!

module.exports.reviewsReadOne = function (req, res) {
  Loc
    .findById(req.params.locationid)
    .select('name reviews')
    .exec(
    function(err, location) {
      sendJsonResponse(res, 200,location);
    });
};

Here will show me all the result of the query that is this:

{
"_id": "59c0115558d09042f1bd203e",
"name": "Starcups",
"reviews": [
    {
        "author": "Simon Holmes",
        "id": "59c0135658d09042f1bd203f",
        "rating": 5,
        "timestamp": "2013-07-16T03:00:00.000Z",
        "reviewText": "What a great place. I can't say enough good things about this",
        "createdOn": "2017-09-22T13:44:22.380Z"
    }
]

}

I want to access the reviews subdocument by id. Then I did:

module.exports.reviewsReadOne = function (req, res) {
  Loc
    .findById(req.params.locationid)
    .select('name reviews')
    .exec(
    function(err, location) {
      var review;
      review = location.reviews.id('59c0135658d09042f1bd203f');
      sendJsonResponse(res, 200,review);
    });
};

And I received the answer

null

I expected to receive the full reviews and not null. I do not know what the problem is here. Does anyone have any ideas there to solve this?

    
asked by anonymous 22.09.2017 / 14:49

1 answer

2

You are looking for:

var review = location.reviews.find(rev => rev.id == '59c0135658d09042f1bd203f');
// ou
var review = location.reviews.find(rev => rev.id == req.params.locationid);

So you look for this array reviews the object whose id property is equal to the string you pass. The find returns the first object that checks the condition.

    
22.09.2017 / 16:36