【问题标题】:How to use search multiple queries together using mongoose? [duplicate]如何使用猫鼬一起搜索多个查询? [复制]
【发布时间】:2021-02-18 00:51:39
【问题描述】:
await User.find({ username: new RegExp(keyword,  'i')}).select('-password')
        .then((profile)=>{
            if(!profile){
                res.json({
                    status: false,
                    message: 'No profiles found'
                })

这是一个单一的搜索。我想一起搜索用户名、组织和全名。怎么可能?

await User.find({ username: new RegExp(keyword,  'i') full_name: new RegExp(keyword,  'i'), organisation: new RegExp(keyword,  'i')}).select('-password')

此代码无效

【问题讨论】:

    标签: node.js mongodb mongoose search


    【解决方案1】:

    您可以使用猫鼬$or 跨字段搜索。

    User.find({ 
      $or: [
        { username: new RegExp(keyword,  'i') }, 
        { organization: new RegExp(keyword,  'i') }, 
        { full_name: new RegExp(keyword,  'i') }
      ]
    })
    

    它在每个文档的usernameorganizationfull_name 字段中搜索关键字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-17
      • 2020-02-21
      • 2020-05-30
      • 2017-08-16
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多