[英]Query mongoose returns no results with $regex
Trying to build a mongoose query with regex but for some reason it always returns zero results. 尝试使用正则表达式构建猫鼬查询,但由于某种原因,它始终返回零结果。
I have a model called Place with value wind_direction. 我有一个名为Place的模型,其值是wind_direction。 wind_direction is a string and looks something like this:
wind_direction是一个字符串,看起来像这样:
place.wind_direction = "SW, WSW, W, WNW, NW, NE, ENE, E";
I get values through a form, in this case "W, WNW, NW" and try to build a regex like this: 我通过一种形式(在这种情况下为“ W,WNW,NW”)获取值,并尝试构建这样的正则表达式:
var string = JSON.stringify(req.body.wind_direction)
string = string.replace(/[\[\]"]+/g,'').split(",")
var reg = ""
for(var i = 0; i < string.length; i++){
reg += "\b" + string[i] + "\b|";
}
reg = "/" + reg.substring(0, reg.length - 1) + "/";
query.wind_direction = { "$regex": reg, "$options": "i" }
When i console.log my query it looks like this: 当我console.log我的查询时,它看起来像这样:
{ wind_direction: { '$regex': '/\bW\b|\bWNW\b|\bNW\b/', '$options': 'i' } }
Then when I run a simple query with Place.find(query, function(req,res... it returns no results. But when I test my regex in an online regex tester it works. 然后,当我使用Place.find(query,function(req,res ...)运行简单的查询时,它不会返回任何结果。但是,当我在在线正则表达式测试器中测试正则表达式时,它将起作用。
It appears that your req.body.wind_direction
is already an array that you may use to build the alternation pattern, there is no need to JSON.stringify
this array. 看来您的
req.body.wind_direction
已经是一个可用于构建交替模式的数组,不需要JSON.stringify
此数组。 To build an alternation, you may use arr.join("|")
. 要构建替代项,可以使用
arr.join("|")
。
In order to avoid repeating \\b
, you may group all the alternatives, and a non-capturing group suits here best: \\b(?:term1|term2|termN)\\b
. 为了避免重复
\\b
,您可以将所有备选方案分组,并且非捕获组最适合这里: \\b(?:term1|term2|termN)\\b
。
You may use 您可以使用
query.wind_direction = { "$regex": new RegExp("\\b(?:" + req.body.wind_direction.join("|") + ")\\b"), "$options": "i" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.