Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the results containing a given substring with spaces in mongoose

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!

like image 688
Masiar Avatar asked Oct 30 '22 08:10

Masiar


1 Answers

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.

like image 56
Redu Avatar answered Nov 14 '22 10:11

Redu