11

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?

Shog9
  • 156,901
  • 35
  • 231
  • 235
ac360
  • 7,735
  • 13
  • 52
  • 91

1 Answers1

26

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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294