【问题标题】:Mongodb search query with populate带有填充的MongoDB搜索查询
【发布时间】:2022-09-30 23:48:40
【问题描述】:

你好,我在 MongoDB 中有 3 个集合,Client AgentLetter 和一个律师

客户

{
_id:\"62bd0d557e6411a15d809bb4\"
,FirstName:\"John\",
LastName:\"Doe\",
Mobile\":\"182-333-8822\",
\"Active\":true,
}

律师

{
_id:\"62bd0d557e6411a15d809bb4\",
 email:johndoe@gmail.com,
,FirstName:\"John\",
LastName:\"Doe\",
Mobile\":\"182-333-8822\",
\"Active\":true,
}

代理信

{
_id:\"62bd0d557e6411a15d809bb4\",
client: [{ type: mongoose.Schema.Types.ObjectId, ref:\'client\' }],
lawyer: [{ type: mongoose.Schema.Types.ObjectId, ref:\'lawyer\' }],
number:\"Doe\",
type:\"all\",
placeOut:\"Suli-court\",
note:\"\"
}

我在与客户和律师有关的代理信表上有搜索输入 当用户搜索“John”之类的内容时,请与律师一起返回文件 客户端如果文本不匹配 placeOut FirstName 和 LastName 返回 [] 我试过这个,但在某些情况下没有用,它不能在 agentletter 上得到 placeOut

 AgentLetter.find().populate({ 
    path  : \'lawyer client\',
    select:\"FirstName LastName\",
    match : {
          $or:[
     { FirstName : {
          $regex: req.params.text, 
          $options: \'i\' 
      }},
      { LastName : {
        $regex: req.params.text, 
        $options: \'i\' 
    }},
// { placeOut : {
//       $regex: req.params.text, 
//       $options: \'i\' 
//    }},
    ]
  }}).exec()

有人知道如何解决这个问题吗?谢谢。

    标签: node.js mongodb mongoose


    【解决方案1】:

    如果您需要populate 多个引用,您应该分别声明它们。
    此外,如果您需要过滤 placeOut,您应该将条件放在 find 查询中:

    const select = 'FirstName LastName';
    const match = {
      $or: [
        {
          FirstName: {
            $regex: req.params.text,
            $options: 'i',
          },
        },
        {
          LastName: {
            $regex: req.params.text,
            $options: 'i',
          },
        },
      ],
    };
    
    AgentLetter.find({ placeOut: { $regex: req.params.text, $options: 'i' } })
      .populate({
        path: 'client',
        select: select,
        match: match,
      })
      .populate({
        path: 'lawyer',
        select: select,
        match: match,
      })
      .exec();
    

    【讨论】:

    • 这不是搜索的好方法。看,如果没有 placeOut 匹配,它不会带回任何东西,即使它可能是律师的名字。
    • 我认为我的问题很清楚,但使用流行并不好,
    • 我编辑了这个问题,你能再看看吗,谢谢你的时间。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2018-12-05
    • 2013-11-03
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多