Best way to perform a full text search in MongoDB and Mongoose Best way to perform a full text search in MongoDB and Mongoose mongoose mongoose

Best way to perform a full text search in MongoDB and Mongoose


You can add a text index to your Mongoose schema definition that lets you use the $text operator in your find queries to search all fields included in the text index.

To create an index to support text search on, say, name and profile.something:

var schema = new Schema({  name: String,  email: String,  profile: {    something: String,    somethingElse: String  }});schema.index({name: 'text', 'profile.something': 'text'});

Or if you want to include all string fields in the index, use the '$**' wildcard:

schema.index({'$**': 'text'});

This would enable you to performed a paged text search query like:

MyModel.find({$text: {$search: searchString}})       .skip(20)       .limit(10)       .exec(function(err, docs) { ... });

For more details, read the full MongoDB Text Indexes documentation.