Full-Text Search in Node JS with Mongoose
Asked Answered
E

3

10

I'm trying to perform a full-text search on an array of strings in Mongoose and I am getting this error:

{ [MongoError: text index required for $text query]
  name: 'MongoError',
  message: 'text index required for $text query',
  waitedMS: 0,
  ok: 0,
  errmsg: 'text index required for $text query',
  code: 27 }

However, I do have a text index declared on the field on the User Schema and I confirmed that the text index has been created because I am using mLab. I am trying to perform a full-text search on fields

Here Is My User Schema:

var userSchema = mongoose.Schema({
        local: {
            firstName: String,
            lastName: String,
            username: String,
            password: String,
            fields: {type: [String], index: true}
        }
});

Here is My Code for the Full-Text Search:

User.find({$text: {$search: search}}, function (err, results) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(results);
                }
        });
Electrodynamic answered 25/11, 2016 at 14:10 Comment(3)
Which mogoose version are you using?Spyglass
Currently using Mongoose 4.7.0Electrodynamic
you need to create a text index on your fields: exampleFlotage
S
13

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.

Spousal answered 25/11, 2016 at 14:22 Comment(0)
S
8

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

Spyglass answered 25/11, 2016 at 14:18 Comment(0)
T
0

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 strings in queries.
MongoDB uses Perl compatible regular expressions (i.e. “PCRE” ) version 8.42 with UTF-8 support.

To use $regex, use one of the 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> }
Telephonic answered 17/8, 2020 at 12:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.