【问题标题】:find mongoose matching items inside an array of objects在对象数组中查找 mongoose 匹配项
【发布时间】:2021-07-08 02:26:33
【问题描述】:

我有一个带有对象数组的猫鼬模式... 我试图在数组中只匹配userID,但是如果只有一个匹配,数组就会返回所有用户。 我在节点 js 上有以下内容

app.get("/myanswers/:id", async (req, res) => {
  try {
    const q = await posts.find(
      { "postAnswer.userID": req.params.id },
      "postAnswer.answer postAnswer._id postAnswer.user postAnswer.userID"
    );
    res.json(q);
  } catch (error) {
    res.send(error);
  }
});

我得到了这个结果:

[
    {
        "_id": "6074f2648e9f41497438b37a",
        "postAnswer": [
            {
                "_id": "6074f3858e9f41497438b37b",
                "userID": "60579272980cb93ea8a91140",
                "user": "admin",
                "answer": "Kakashi ????‍????"
            }
        ]
    },
    {
        "_id": "6074f4768e9f41497438b37c",
        "postAnswer": [
            {
                "_id": "6074f5338e9f41497438b37e",
                "userID": "6074f4f98e9f41497438b37d",
                "user": "barrym",
                "answer": "here's the correct sequence. table, add row table headers close row. add row add table data close row close table."
            },
            {
                "_id": "6074f5808e9f41497438b37f",
                "userID": "60579272980cb93ea8a91140",
                "user": "admin",
                "answer": "with TH and TD!"
            }
        ]
    }
]

我只想要完全匹配,所以用户 barrym 不应该出现

【问题讨论】:

    标签: node.js mongodb mongoose postman


    【解决方案1】:

    演示 - https://mongoplayground.net/p/3BV58F3GiS4

    使用$ (projection)

    注意:- 限制 an 的内容返回第一个元素

    位置 $ 运算符限制 an 的内容以返回与数组上的查询条件匹配的第一个元素。

    db.collection.find(
     { "postAnswer.userID": "6074f4f98e9f41497438b37d"},
     { "postAnswer.$": 1}
    )
    

    【讨论】:

    • 这只会限制结果..不是我需要的。我只需要与postAnswer.userID 匹配的结果
    • @KashifAli 你看演示了吗?预期的输出是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2019-08-17
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多