Full-Text Search in Node JS with Mongoose
For $text
queries to work, MongoDB needs to index the field with a text index. To create this index by mongoose use
fields: {type: [String], text: true}
See here for the MongoDB documentation of text indexes.
You need to add a text index to your schema like below:
userSchema.index({fields: 'text'});
Or use userSchema.index({'$**': 'text'});
if you want to include all string fields
If for some reason adding a test index is not an option, you could also use the regex operator in your aggregation pipeline to match strings.
$regex
Provides regular expression capabilities for pattern matching stringsin queries.
MongoDB uses Perl compatible regular expressions (i.e.“PCRE” ) version 8.42 with UTF-8 support.To use $regex, use one ofthe following syntaxes:
{ <field>: { $regex: /pattern/, $options: '<options>' } }{ <field>: { $regex: 'pattern', $options: '<options>' } }{ <field>: { $regex: /pattern/<options> } }
In MongoDB, you can also use regular expression objects (i.e./pattern/) to specify regular expressions:
{ <field>: /pattern/<options> }