5

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!

Masiar
  • 20,450
  • 31
  • 97
  • 140
  • 1
    Actually there is no reason the partials you say you are sending would not match, perhaps you are really pluralizing the words. This really depends on your "search" needs. Are all words important? Is the whitespace important? Also check that you are not including other characters that would be messing with the search. – Blakes Seven Mar 07 '16 at 08:02

2 Answers2

1

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.

Redu
  • 25,060
  • 6
  • 56
  • 76
1

Your research is very useful I found my answer from your question and I just read Mongoose and MongoDb documentation and got answer https://docs.mongodb.com/manual/reference/operator/query/regex/#op._S_regex

Vehicle.find({ registrationNo: { "$regex": registrationNo, "$options": "ix" }}, function (err, vehicle) {}

// { <field>: { $regex: /pattern/, $options: '<options>' } }

Just provided options (i) will ignore case and (x) will truncate spaces from pattern

Screenshot from MongoDb documentation:

enter image description here

Draken
  • 3,134
  • 13
  • 34
  • 54
Rohit Luthra
  • 1,256
  • 17
  • 27