Antonoff
@Antonoff
Разработчик

Проблема с REST API (Node, Express, Mongo)?

У меня есть апи с locations, для каждого location - есть список reviews. Написать api ко всем locations получилось, выбрать из списка определенный review зная его id, не вышло. Всё ломается тут
review = location.reviews.id(req.params.reviewid);
, хотя location.reviews =
[ { author: 'Simon Holmes',
    id: 57acda33cec290c7a1466cf2,
    rating: 5,
    timestamp: Thu Jul 16 2015 00:00:00 GMT+0100 (GMT Summer Time),
    reviewText: 'What a great place. I can\'t say enough good things about it.',
    createdOn: Sun Aug 14 2016 19:21:34 GMT+0100 (GMT Summer Time) },
  { author: 'Simon Holmes',
    id: 57acdcb3cec290c7a1466cf7,
    rating: 5,
    timestamp: Wed Jun 10 2015 00:00:00 GMT+0100 (GMT Summer Time),
    reviewText: 'What a great place. I can\'t say enough good things about it.',
    createdOn: Sun Aug 14 2016 19:21:34 GMT+0100 (GMT Summer Time) },
  { author: 'Simon Holmes',
    id: 57acdcd1cec290c7a1466cf8,
    rating: 2,
    timestamp: Mon Jun 29 2015 00:00:00 GMT+0100 (GMT Summer Time),
    reviewText: 'What a great place. I can\'t say enough good things about it.',
    createdOn: Sun Aug 14 2016 19:21:34 GMT+0100 (GMT Summer Time) } ]

а
req.params.reviewid
равняется
57acda33cec290c7a1466cf2

Controller:
module.exports.reviewsReadOne = function(req, res) {
    console.log("Getting a single review");
    if (req.params && req.params.locationid && req.params.reviewid) {
        Loc
            .findById(req.params.locationid)
            .select('name reviews')
            .exec(
                function(err, location) {
                    // console.log(location);
                    var response, review;

                    if (!location) {
                        sendJSONresponse(res, 404, {
                            "message": "locationid not found"
                        });
                        return;
                    } else if (err) {
                        sendJSONresponse(res, 400, err);
                        return;
                    }

                    console.log(req.params);
                    console.log(location);

                    if (location.reviews) {
                        review = location.reviews.id(req.params.reviewid); // null
                        if (!review) {
                            sendJSONresponse(res, 404, {
                                "message": "reviewid not found"
                            });
                        } else {
                            response = {
                                location: {
                                    name: location.name,
                                    id: req.params.locationid
                                },
                                review: review
                            };
                            sendJSONresponse(res, 200, response);
                        }
                    } else {
                        sendJSONresponse(res, 404, {
                            "message": "No reviews found"
                        });
                    }
                }
            );
    } else {
        sendJSONresponse(res, 404, {
            "message": "Not found, locationid and reviewid are both required"
        });
    }
};


Когда делаю запрос через Postman
http://localhost:1337/api/locations/57acd67fcec290c7a1466cf0/reviews/57acda33cec290c7a1466cf2


Получаю в ответ:
{
  "message": "reviewid not found"
}


Ответ в Node консоле:
Mongoose connected to mongodb://127.0.0.1:27017/Loc8r
Getting a single review
{ locationid: '57acd67fcec290c7a1466cf0',
  reviewid: '57acda33cec290c7a1466cf2' }
{ _id: 57acd67fcec290c7a1466cf0,
  name: 'Starcups',
  reviews:
   [ { author: 'Simon Holmes',
       id: 57acda33cec290c7a1466cf2,
       rating: 5,
       timestamp: Thu Jul 16 2015 00:00:00 GMT+0100 (GMT Summer Time),
       reviewText: 'What a great place. I can\'t say enough good things about it.',
       createdOn: Sun Aug 14 2016 19:14:38 GMT+0100 (GMT Summer Time) },
     { author: 'Simon Holmes',
       id: 57acdcb3cec290c7a1466cf7,
       rating: 5,
       timestamp: Wed Jun 10 2015 00:00:00 GMT+0100 (GMT Summer Time),
       reviewText: 'What a great place. I can\'t say enough good things about it.',
       createdOn: Sun Aug 14 2016 19:14:38 GMT+0100 (GMT Summer Time) },
     { author: 'Simon Holmes',
       id: 57acdcd1cec290c7a1466cf8,
       rating: 2,
       timestamp: Mon Jun 29 2015 00:00:00 GMT+0100 (GMT Summer Time),
       reviewText: 'What a great place. I can\'t say enough good things about it.',
       createdOn: Sun Aug 14 2016 19:14:38 GMT+0100 (GMT Summer Time) } ] }
GET /api/locations/57acd67fcec290c7a1466cf0/reviews/57acda33cec290c7a1466cf2 404 27.935 ms - 32
  • Вопрос задан
  • 396 просмотров
Пригласить эксперта
Ответы на вопрос 2
Voronar
@Voronar
Code typesetter
Ответ на наш вопрос тут.
И мне кажется понятно, откуда у нас id, а не _id.
Ты ведь так добавлял данные через консоль?

Цитата:
Putting it all together shows something like the following code snippet:
> db.locations.update({ name: 'Starcups'}, {
  $push: {
    reviews: {
      author: 'Simon Holmes',
      id: ObjectId(), //INCORRECT
      rating: 5,
      timestamp: new Date("Jul 16, 2013"),
      reviewText: "What a great place. I can't say enough good things about it."
    }
  }
});


Отсюда скорее всего и неправильный результат.
Ответ написан
Antonoff
@Antonoff Автор вопроса
Разработчик
То что ответил автор книги:

In the Mongo shell try something like this to add an _id to a review

db.locations.update(
  { "name": "INSERT A LOCATION NAME HERE" },
  {
    $set : {
      "reviews.0._id" : ObjectId()
    }
  }
)


This will add an _id property with an objectId value to the first review subdocument in the location you specify in the command.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 05:01
999999 руб./за проект
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект