mongoose查找并返回res.status.json



我正在开发一个显示公告牌列表的API。

同时,它还显示了一个最新的帖子。

在控制器中,我像这样编码

exports.boards_get_all = (req, res, next)=>{
Board.find()
.exec()
.then(boards=>{
res.status(200).json({
count: boards.length,
boards: boards.map(board=>{
return {
board: {
id:board._id,
name: board.name,
order: board.order
},
post : Post.findOne({boardId:board._id})
.exec()
.then(posts=>{
console.log(posts)
return posts;
}
)
}
})
})
})
}

我使用findOne((并尝试返回Post发现的

但回邮不起作用。只返回空值。

结果:

{
"count": 1,
"boards": [
{
"board": {
"id": "5eb23f1fed38dc5dfc2debfd",
"name": "QnA board",
"order": 1
},
"post": {}
}
]
}

我认为我使用findOne((的方法不对。。。

我想得到这样的结果

{
"count": 1,
"boards": [
{
"board": {
"id": "5eb23f1fed38dc5dfc2debfd",
"name": "QnA board",
"order": 1
},
"post": {
_id: 5eb364a27989ab6f414fcdb1,
userId: 5eb2aad669738d67b5497f3a,
boardId: 5eb23f1fed38dc5dfc2debfd,
type: 1,
title: 'this is a latest post in QnA board',
content: 'Sample content',
like: 0,
comment: 0,
view: 1,
date: 2020-05-07T01:30:10.957Z,
thumb: 'pic url',
__v: 0
}
}
]
}

post是{},因为res.status(200).json()findOne回调返回值之前执行并返回。

要解决此问题,您需要在调用res.status(200).json()之前从数据库中获取post文档。

相关内容

最新更新