如何在mongoDB中通过postId为嵌套数组查找发出get请求

bvk5enib  于 2023-05-17  发布在  Go
关注(0)|答案(1)|浏览(95)

如何通过postId在嵌套数组“comments”中获取单个注解?

{
    "_id": "64200557af767187bcbcfc6c",
    "username": "ascarids",
    "usersAt": "@osteoids",
    "comments": [
        {
            "username": "osteoids",
            "photo": "",
            "comments": "Now it would def work.",
            "usersAt": "@osteoids",
            "postId": "64200557af767187bcbcfc6c",
            "createdAt": 1682006033770
        },
        {
            "username": "osteoids",
            "photo": "",
            "comments": "Now let's try something",
            "usersAt": "@osteoids",
            "postId": "64200557af767187bcbcuy6c",
            "createdAt": 1683486129151,
            "like": [],
            "newId": "11621edadd13e67431d40e45"
        }
    ],
    "createdAt": "2023-03-26T08:41:59.187Z",
    "updatedAt": "2023-05-07T19:02:50.015Z",
    "__v": 0
}

我试着用这种方式写它,但它不起作用,我一直看到像$elemMatch和$map和其他一些方法这样的东西。我不确定是不是我访问数组的深度不够,还是我写错了。

router.get(`:id/:postId`, async (req, res) => {
  const id = req.params.id;
  const postId = req.params.postId
  let comments;
  try {
    comments = await Post.findById({comments: {postId: postId}})
  } catch (err) {
    res.status(500).json(err);
  }
  if (!comments) {
    return res.status(404).json({ message: "No posts found" });
  }

  return res.status(200).json({ comments });
})

但我真正想要的是嵌套数组

//Writing it this way is what returns the above json format
router.get("/:id", async (req, res) => {
  try {
    const post = await Post.findById(req.params.id);
    res.status(200).json(post);
  } catch (err) {
    res.status(500).json(err);
  }
});
ruarlubt

ruarlubt1#

一种选择是使用投影,这是find查询中的第二个{}

comments = await Post.find(
  {_id: _id, comments: {$elemMatch: {postId: req.params.postId}}},
  {"comments.$": 1}
)

了解它在playground example上的工作原理

  • 请注意,mongoose findById需要的是文档的_id,而不是嵌套的id。在此选项中,您还将使用postId,以便稍后可以对其进行投影

相关问题