Заполнение атрибута, который представляет собой массив идентификаторов, используя mongoose populate - PullRequest
0 голосов
/ 27 сентября 2018

У меня есть объект, который выглядит следующим образом:

Topic
 {
    "posts": [
        "5baabfeb87a1401432791534",
        "5bac21814a0f9a2262a77f1b"
    ],
    "_id": "5ba06e74dbc05f039490438c",
    "topic": "new topic",
    "description": "this is the description",
    "date": "2018-09-18T03:18:12.062Z",
    "__v": 2
}

Я пытаюсь вернуть Topic.posts в виде массива записей, используя заполнение mongoose.это то, что я пытаюсь

router.get('/:topicId/posts', (req,res) => {
  const {topicId} = req.params
  Topic.findById(topicId)
  .then(topic => res.json(topic.posts.populate('posts')) 
     )
  .catch(err => res.send(err))
});
//getting a {} blank object its not even an array?

если возможно, идентифицируйте его как возвращающий весь объект темы с заполненным массивом.

Topic
  {
    "posts": [
        {
        "_id": "5bac21814a0f9a2262a77f1b",
         "post": "post 2",
         "description": "blah blah",
        },
        {
          "_id": "5baabfeb87a1401432791534",
           "post": " this is a post",
           "description": "blah blah blah"
          }
    ],
    "_id": "5ba06e74dbc05f039490438c",
    "topic": "new topic",
    "description": "this is the description",
    "date": "2018-09-18T03:18:12.062Z",
    "__v": 2
}

Какие у меня варианты?

1 Ответ

0 голосов
/ 27 сентября 2018

разобрался

router.get('/:topicId/posts', (req,res) => {
  const {topicId} = req.params
  Topic.findById(topicId) //I thought you had to map the array but populate iterates for you
  .populate('posts')
  .then(topic => res.json(topic))
  .catch(err => res.send(err))
});
...