What is the recommended way to drop indexes using Mongoose?

I need to create several deployment scripts like data migration and fixtures for a MongoDB database and I couldn't find enough information about how to drop indexes using Mongoose API. This is pretty straight-forward when using the official MongoDB API:

To delete all indexes on the specified collection: db.collection.dropIndexes();

However, I would like to use Mongoose for this and I tried to use executeDbCommand adapted from this post, but with no success:

mongoose.connection.db.executeDbCommand({ dropIndexes: collectionName, index: '*' },
  function(err, result) { /* ... */ });

Should I use the official MongoDB API for Node.js or I just missed something in this approach?

Answers


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
});

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.

Need Your Help

How to pass parameters or arguments into a gradle task

variables groovy parameters gradle

I have a gradle build script into which I am trying to include Eric Wendelin's css plugin - http://eriwen.github.io/gradle-css-plugin/