Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
npclaudiu Avatar asked Oct 22 '12 15:10

npclaudiu


2 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
});
like image 124
JohnnyHK Avatar answered Sep 29 '22 12:09

JohnnyHK


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

like image 23
J.Wolfe Avatar answered Sep 29 '22 12:09

J.Wolfe