【问题标题】:How to query findOne() in mongoose such that we get subset of array of documents which satisfy particular condition?如何在猫鼬中查询 findOne() 以获得满足特定条件的文档数组的子集?
【发布时间】:2020-02-22 02:20:13
【问题描述】:

当我查询这个时

const pendingOfThisShop = await ShopProfile.findOne({ shop: req.shop.id, "shopsAffiliate.status":"pending" },{ shopsAffiliate: 1, _id: 0 }

我得到一个这样的对象

{
"shopsAffiliate": [
    {
        "status": "approved",
        "_id": "5db315a6de255a4444b0987b",
        "affiliateId": "5db31263a362ed4ed84c7ad5"
    },
    {
        "status": "pending",
        "_id": "5db315c5de255a4444b0987d",
        "affiliateId": "5db2b4713db4101e48836f0a"
    }
]}

我同时获得状态:“已批准”和状态:“待定”。我只想在 shopAffiliate 数组中获取那些状态为“待定”的对象。我该怎么办?

【问题讨论】:

    标签: arrays node.js json mongodb mongoose


    【解决方案1】:

    试试这个:

    const pendingOfThisShop = await ShopProfile.findOne({ shop: mongoose.Types.ObjectId(req.shop.id), "shopsAffiliate.status":"pending" },{ "shopsAffiliate": {'$elemMatch': {"status":"pending"}}, _id: 0 });
    

    【讨论】:

    • 我试过了,它说 -> 不能将 $elemMatch 与字符串一起使用。
    【解决方案2】:

    我同时获得状态:“已批准”和状态:“待定”

    您的查询正在返回预期结果。

    shopsAffiliate 是一个嵌套文档数组。 shopsAffiliate 本身是 ShopProfile 集合内文档的一部分。您的查询会检查 ShopProfile 中满足以下 2 个条件的任何文档

    1. shop: req.shop.id
    2. "shopsAffiliate.status":"pending"

    当它找到任何符合上述两个条件的文档时,它会返回整个文档。它不关心匹配文档的shopsAffiliate 数组中是否有其他文档不具有pending 状态,它只需要shopsAffiliate 数组中找到至少1 个具有pending 状态的文档,一旦找到,它就会返回整个文档

    我只想在 shopAffiliate 数组中获取那些具有 “待定”状态。我该怎么办?

    您可以使用aggregation operation 来获得想要的结果

    const pendingOfThisShop = await ShopProfile.aggregate([
          {
              $match: {
                  shop: req.shop.id,
                  "shopsAffiliate.status": "pending"
              }
          },
          {
              $unwind: "$shopsAffiliate"
          },
          {
              $match: { "shopsAffiliate.status": "pending" }
          }
    ]);
    

    【讨论】:

    • 谢谢我正在使用猫鼬所以将 req.shop.id 转换为 ObjectId 我只需用这个 mongoose.Types.ObjectId(req.shop.id) 替换 req.shop.id。它奏效了。这是工作的确切代码const pendingOfThisShop = await ShopProfile.aggregate([ { $match: { shop: mongoose.Types.ObjectId(req.shop.id), "shopsAffiliate.status": "pending" } }, { $unwind: "$shopsAffiliate" }, { $match: { "shopsAffiliate.status": "pending" } }, { $project: { shopsAffiliate: 1 } } ]);
    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2012-09-30
    • 2012-01-22
    相关资源
    最近更新 更多