0

I have a regex search in my code for getting names in my db by the given string. The problem I'm having is that if I have a name "Jim" and a name "Jimmy", I always get the "Jimmy" for some reason.

let regexp = new RegExp(userName, "i");
let name = await names.findOne({ name: regexp });

So when I type in "Jimmy" I get Jimmy, "Jimm" I get Jimmy, all good, but when I try to find "Jim" I get Jimmy, so there's no way for me to get Jim.

Also I can't find names if they have ( or ) ? Ex: Tom (Thomas), and i search exactly "Tom (Thomas)" it doesn't find it at all, but that might be a Mongoose problem.

Torqus
  • 41
  • 4
  • can you please put the regex ? – Aziz.G Mar 05 '19 at 22:32
  • Instead of finding just one match, get all the matches. Then calculate the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) from the seach string to all the matches to find the closest one. – Barmar Mar 05 '19 at 22:50
  • `(` and `)` have special meaning in regular expressions, you need to escape them if you want to match them literally. Are you sure you need to use a regexp in the first place? – Barmar Mar 05 '19 at 22:51
  • I would escape them, but they are inside a variable, and the variable is an input by the user so I need a way to tell regexp to ignore the () or something – Torqus Mar 05 '19 at 23:30
  • Are you sure you need to use a regexp at all? Can you use `String.prototype.includes()` to look for a literal substring? – Barmar Mar 06 '19 at 15:47

1 Answers1

0

I think this is a problem with how you're ordering your database, or at least the results that you query from it. You can either sort the table, or sort your results after you query them.

Try using one of these (alphabetical or reverse alphabetical):

let name = await names.sort({ name: 1 }).findOne({ name: regexp });
let name = await names.sort({ name: -1 }).findOne({ name: regexp });

For your second question, it looks like what you want to investigate "Fuzzy Matching" - so that things like Tom can return results like Thomas.

Try taking a look at this:

Fuzzy Searching with Mongodb?

Addison
  • 7,322
  • 2
  • 39
  • 55