How to use autoIndex in mongoose / mongodb

Viewed 932

I am using mongodb with mongoose in my project. I am trying to use text indexes so i can implement a search functionality. I have set auotIndex option to true but i still get the following error "MongoError: text index required for $text query" this indicates text indexes have not been generated and therefor autoIndex is not working if i am not mistaken.

By the way i know that autoIndex should not be in production ready applications because it is heavy but the project i am working on is just for learning purposes.

// Database start upp
(async () => {
    const DB_URI = "mongodb://localhost:27017/photogram-db";

    const DB_SETTINGS = {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useCreateIndex: true,
        autoIndex: true
    };

    await mongoose.connect(DB_URI, DB_SETTINGS);
})();


// Person model / schema
const PersonSchema = new Schema({
    firstName: String,
    lastName: String,
    username: String,
});

PersonSchema.index({
    firstName: "text",
    lastName: "text",
    username: "text"
});

const PersonModel = model("Person", PersonSchema);
1 Answers

Text index creation takes some time, so I guess it's not ready when you search with text? Maybe you can try to listen to the index event when the index is done.

 PersonModel.on('index', function(error) {
      console.log('index is finished');
  });
Related