【问题标题】:mongoose find and return res.status.jsonmongoose 查找并返回 res.status.json
【发布时间】:2020-08-22 06:21:01
【问题描述】:

我正在开发一个显示公告板列表的 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
                    }
            }
        ]
    }

【问题讨论】:

    标签: node.js json mongodb mongoose postman


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-09
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多