猫鼬查找并返回res.status.json

问题描述 投票:0回答:1

我正在开发一个显示公告板列表的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()并尝试返回所找到的帖子

但是回邮无效。只需返回空值。

结果:

{
    "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
                    }
            }
        ]
    }
node.js json mongodb mongoose postman
1个回答
0
投票

该帖子为{},因为在res.status(200).json()回调返回值之前执行并返回了findOne

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

© www.soinside.com 2019 - 2024. All rights reserved.