Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a search query for partial string matches in Mongoose?

I'm new to Mongoose.js and I'm wondering how to create a simple Mongoose query that returns values containing the characters in the order that they were submitted.

This will be for an autocomplete form which needs to return cities with names that contain characters input into the search field. Should I start with a .where query?

like image 765
ac360 Avatar asked Nov 25 '13 20:11

ac360


1 Answers

You could find by regexp, which should allow you to search in a flexible (although not extremely fast) way. The code would be something similar to;

var input = 'ln';  // the input from your auto-complete box

cities.find({name: new RegExp(input, "i")}, function(err, docs) {
   ...
});

Of course, you could preprocess the string to make it match from the start (prepend by ^), from the end (append by $) etc. Just note that matching against arbitrary parts of long strings may be slow.

like image 83
Joachim Isaksson Avatar answered Oct 11 '22 14:10

Joachim Isaksson