Categories
JavaScript Answers

How to perform a full text search in MongoDB and Mongoose and JavaScript?

Spread the love

To perform a full text search in MongoDB and Mongoose and JavaScript, we set the $text.$search property.

For instance, we write

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

to create the schema schema.

And we add an index to it by calling `schema.index with the fields we want to index.

We add 'text' indexes to the name and profile.something fields.

Then we do a fuzzy search with

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

to call find with the $text.$search property set to the query we want to run.

And we get the results returned from docs.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *