【问题标题】:Find after populate in array of object在对象数组中填充后查找
【发布时间】:2021-07-25 08:40:27
【问题描述】:

我想根据“guess.body”“找到”以下项目:

{
        
        "guess": [
           
            {
                "body": "findme",
            }
        ],
        "_id": "608ee73b18a16e39e809203f"
}

此项目位于名为“ask”的集合中,具有以下模型:

const askSchema = new Schema ({
guess: [{type:Schema.Types.ObjectId, ref:'guess'}],

})

为了做到这一点,我尝试了 2 个查询:

  • 第一个:

     const askByGuess = await ask.find().populate("guess").find({"guess.body":"findme"})
     res.status(200).json(askByGuess)
    

返回一个空数组

  • 第二个(基于这个答案:Find after populate mongoose

     const askByGuess = await ask.find().populate({path:"guess", match{body:"findme"}}).exec(function(err, ask) {ask = ask.filter(function(ask) {return ask.guess})})
     res.status(200).json(askByGuess)
    

返回“1”。

有人可以告诉我我做错了什么吗?

谢谢!

【问题讨论】:

    标签: mongoose


    【解决方案1】:

    您不必使用populate,因为guess 属性未引用另一个集合。试试这个:

    const askByGuess = await ask.find({
      guess: {
        $elemMatch: {
          body: "findme"
        }
      }
    })
    res.status(200).json(askByGuess)
    

    这里是工作的 sn-p:https://mongoplayground.net/p/isBMZ3Fa8QB

    【讨论】:

    • 感谢您的帮助。不幸的是,填充是必要的,因为猜测确实指的是另一个集合。这是模型仅供参考。 const askSchema = new Schema ({ alert: {type: Boolean, default: false, required: false}, guess: [{type:Schema.Types.ObjectId, ref:'guess'}] }) 抱歉没有在我的第一条消息。
    【解决方案2】:

    我倾向于同意Find after populate mongoose 中提出的解决方案,但是,如果对于您的特定用例,您可以通过简单的聚合管道获得:

    $unwind:填充 guess 字段。
    $lookup:执行左外连接。
    $match:最终匹配您的搜索词。

    db.ask.aggregate({
      $unwind: "$guess"
    },
    {
      $lookup: {
        from: "guess",
        localField: "guess",
        foreignField: "_id",
        as: "guess"
      }
    },
    {
      $match: {
        "guess.body": "test"
      }
    })
    

    这是一个有效的 sn-p:https://mongoplayground.net/p/bJgC4rSvb_9

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 2022-01-24
      • 2016-01-19
      • 2022-08-02
      • 2013-03-10
      • 2021-08-16
      • 1970-01-01
      • 2013-06-30
      相关资源
      最近更新 更多