I found many solutions to this problem but none works. Let's say that I have the following schema:
var Schema = new Schema ({
name : String,
url : String
});
And let's say that one of my entries is:
{
name : "Product and Services",
url : "www.randomurl.com"
}
I want to be able to retrieve this result passing a substring, for example " and services"
or "product and"
and so on. I tried the following (partialToSearch
is the partial string):
Schema.find({name: { "$regex": partialToSearch, "$options": "i" }}, function(err, res){...});
And also tried the following:
Schema.find({name: new RegExp(partialToSearch, "i")}, function(err, res) {...});
Both of them work when I only pass "product"
"and"
or "services"
but when I put a space and another word no result is found (res is empty).
Thanks!
It's most probably because you are not converting the whitespaces into "\s"
(\s+
is better though) character like
"$regex": new RegExp(partialToSearch.replace(/\s+/g,"\\s+"), "gi");
I haven't had the chance to try it out with mongoose but i am pretty sure it's fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With