【问题标题】:Populating an attribute that's an array of Ids using mongoose populate使用 mongoose populate 填充作为 Id 数组的属性
【发布时间】:2018-09-27 09:10:53
【问题描述】:

我有一个看起来像这样的对象:

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

我正在尝试使用 mongoose 的填充将 Topic.posts 作为记录数组返回。这就是我正在尝试的。

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?

如果可能 id 喜欢它返回填充数组的整个主题对象。

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
}

我有什么选择?

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    想通了

    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))
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-18
      • 2023-03-30
      • 2016-02-14
      • 2017-05-07
      • 2014-09-04
      • 2019-12-06
      • 2014-10-27
      • 2021-04-26
      • 2019-02-13
      相关资源
      最近更新 更多