What is the recommended way to drop indexes using Mongoose? What is the recommended way to drop indexes using Mongoose? mongoose mongoose

What is the recommended way to drop indexes using Mongoose?


To do this via the Mongoose model for the collection, you can call dropAllIndexes of the native collection:

MyModel.collection.dropAllIndexes(function (err, results) {    // Handle errors});

Update

dropAllIndexes is deprecated in the 2.x version of the native driver, so dropIndexes should be used instead:

MyModel.collection.dropIndexes(function (err, results) {    // Handle errors});


If you want to maintain your indexes in your schema definitions with mongoose (you probably do if you're using mongoose), you can easily drop ones not in use anymore and create indexes that don't exist yet. You can just run a one off await YourModel.syncIndexes() on any models that you need to sync. It will create ones in the background with .ensureIndexes and drop any that no longer exist in your schema definition. You can look at the full docs here:https://mongoosejs.com/docs/api.html#model_Model.syncIndexes


It looks like you're attempting to drop all of the indexes on a given collection.

According to the MongoDB Docs, this is the correct command.

... I tried to use executeDbCommand adapted from this post, but with no success:

To really help here, we need more details:

  • What failed? How did you measure "no success"?
  • Can you confirm 100% that the command ran? Did you output to the logs in the callback? Did you check the err variable?
  • Where are you creating indexes? Can you confirm that you're not re-creating them after dropping?
  • Have you tried the command while listing specific index names? Honestly, you should not be using "*". You should be deleting and creating very specific indexes.