简体   繁体   English

如何在带有2个不同键的正则表达式中使用mongo'$ or'运算符?

[英]How to use mongo '$or' operator with regex with 2 different keys?

Working on a search bar to search through a list of items (items have name and address) in react with mongo 在搜索栏上工作以与mongo反应搜索项目列表(具有名称和地址的项目)

the keys are called 'name' and 'Address' 这些键称为“名称”和“地址”

I want the search bar to to display based on user input, it could be name or address based on regex 我希望搜索栏根据用户输入显示,可以是基于正则表达式的名称或地址

But I can only get the query to use one of the keys and not both 但是我只能使查询使用键之一,而不能同时使用

queryData['name'] = { $regex: searchField.replace(/[^a-zA-Z0-9-_@.]/g,''), $options: 'i' } // this lets me search through name array

When I change 'name' to address, it will use the address array for searchbar how can I use both name and address? 当我将“名称”更改为地址时,它将使用地址数组作为搜索栏,我如何同时使用名称和地址?

I tried doing 我试着做

queryData['$or'] = [
    { name: {regex: searchField.replace(...), $options: 'i' }},
    { address: {regex: searchField.replace(...),$options:'i'}}
]

But the above method does not work, no errors on inspector, is my syntax off ? 但是上述方法不起作用,检查器上没有错误,我的语法关闭了吗? What else can I try? 我还能尝试什么? Thanks in advance. 提前致谢。

The only thing is that in your syntax you don't have the $ in front of your regex strings. 唯一的事情是,在您的语法中,您的正则表达式字符串前没有$。 I tried your example on a MongoDB database that I have running locally and it seems to work as long as you use $regex, not regex, so (in my case): 我在本地运行的MongoDB数据库上尝试了您的示例,只要您使用$ regex而不是regex,它就可以正常工作,因此(在我的情况下):

 {$or: [{name: {regex: "Energy"}},{category: {regex: "Values"}}]} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM