填充';s使用mongoose填充的ID数组
我有一个像这样的对象:填充';s使用mongoose填充的ID数组,mongoose,mongoose-populate,Mongoose,Mongoose Populate,我有一个像这样的对象: Topic { "posts": [ "5baabfeb87a1401432791534", "5bac21814a0f9a2262a77f1b" ], "_id": "5ba06e74dbc05f039490438c", "topic": "new topic", "description": "this is the description", "date": "2018-09-18T0
Topic
{
"posts": [
"5baabfeb87a1401432791534",
"5bac21814a0f9a2262a77f1b"
],
"_id": "5ba06e74dbc05f039490438c",
"topic": "new topic",
"description": "this is the description",
"date": "2018-09-18T03:18:12.062Z",
"__v": 2
}
我正在尝试使用mongoose的populate将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?
如果可能,我希望它返回整个主题对象,并填充数组
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
}
我的选择是什么?找到了答案
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))
});