我有一个看起来像这样的对象:
Topic
{
"posts": [
"5baabfeb87a1401432791534",
"5bac21814a0f9a2262a77f1b"
],
"_id": "5ba06e74dbc05f039490438c",
"topic": "new topic",
"description": "this is the description",
"date": "2018-09-18T03:18:12.062Z",
"__v": 2
}
im试图使用猫鼬的填充返回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
}
我有什么选择?
答案 0 :(得分: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))
});