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. wind_direction is a string and looks something like this:
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:
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:
{ 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.