如何使用猫鼬一起使用多个搜索查询?

时间:2020-11-05 10:14:52

标签: node.js mongodb mongoose search

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')

此代码不起作用

1 个答案:

答案 0 :(得分:1)

您可以使用猫鼬$or来搜索各个字段。

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

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