Home > Enterprise >  how to set mongoose indexes correctly and test them
how to set mongoose indexes correctly and test them

Time:09-30

I want to set 2 indexes for now, perhaps a 3rd but wanted to know how I can test if they are actually working? Do I need to use with mongo shell or is there a way to check using Node.js during development? I also saw an example of the indexes being created in mongoDb Compass. I am using mongoDb Atlas so wondered if I must just set the index in Compass or do I still need to do it in my mongoose schema?

Also, the mongoose docs say you should set autoIndex to false. Is the below then correct?

const mongoose = require("mongoose");

const Schema = mongoose.Schema;

const userSchema = new Schema({
  firstName: {
    type: String,
  },
  lastName: {
    type: String,
  },
});

userSchema.set("autoIndex", false);
userSchema.index({ firstName: 1, lastName: 1 });

module.exports = mongoose.model("User", userSchema);

CodePudding user response:

There are a bunch of different questions here, let's see if we can tackle them in order.

I want to set 2 indexes for now, perhaps a 3rd

This isn't a question from your side, but rather from mine. What are the indexes that you are considering and what queries will you be running?

The reason I ask is because I only see a single index definition provided in the question ({ firstName: 1, lastName: 1 }) and no query. Normally indexes are designed specifically to support the queries, so the first step towards ensuring a successful indexing strategy is to make sure they align appropriately with the anticipated workload.

how I can test if they are actually working? Do I need to use with mongo shell or is there a way to check using Node.js during development?

There are a few ways to approach this, which include:

  • Using the explain() method to confirm that the winningPlan is using the index as expected. This is often done via the MongoDB Shell or via Compass.
  • Using the $indexStats aggregation stage to confirm that usage counters of the index are incrementing as expected when the application runs.
  • Taking a look at some of the tabs in the Atlas UI such as Performance Advisor or the Profiler which may help alert you to unoptimized operations and missing indexes.

I am using mongoDb Atlas so wondered if I must just set the index in Compass or do I still need to do it in my mongoose schema?

You can use Compass (or the Atlas UI, or the MongoDB Shell) to create your indexes. I would recommend against doing this in the application directly.

Also, the mongoose docs say you should set autoIndex to false. Is the below then correct?

As noted above, I would go further and remove index creation from the application code altogether. There can be some unintended side effects of making the application directly responsible for index management, which is one of the reasons that Mongoose no longer recommends using the autoIndex functionality.

  • Related