Search by id Mongo

Asked

Viewed 606 times

1

Hello guys I’m following the book Getting Mean but I stumbled across a problem I can’t solve. I have a document I show below taking data from Mongo, and in it I have subdocuments in the case Reviews in which I want to take the id.
My problem is that I cannot return the subdocument by id. It always returns 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 every 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. So 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 got the reply

null

I was hoping to receive the Views completely and not null. I don’t know what the problem is here. Does anyone have any ideas on how to solve this ?

  • "this response from my server" - do you mean client or server? because below you speak on server again

  • 1

    My "name"! I think the index is missing [0]: review = location.reviews[0].id(req.params.reviewid);

  • 1

    If the question is clearer the answer is very quick. But I still don’t understand what comes from the server, what comes from the Database and what comes/goes to the client... Can you explain better where the parts of the code you have come from in the question?

  • Cara changed the question. I thought the problem was something with my javascript manipulation, so I applied what I said, it worked to get the other values but the id that is a Mongo method that from what I understood from the book will make the query in the subdocument. Take a read and see if it’s improved.

1 answer

2


What you seek is:

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

So look in this array reviews the object whose property id is the same as the string you pass to it. The find returns the first object that checks the condition.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.