Here is my function to create a mongo index. It only attempts to create it if it does not already exist. It should be easy to modify it to turn it into a deleteIndex function.
Personally, if I had an unnecessary index on a collection, I would use something like robomongo to remove it. For me, indexes need to be created for speed so I need to generally ensure that indexes exist other than not existing. When I start meteor, all my collections ensure they have the appropriate indexes on them by calling this function a couple of times. e.g.
createMongoIndex( ColAuditing, collectionName, 'userAudit', { userId: 1, auditDate: -1 }, {});
createMongoIndex( ColAuditing, collectionName, 'collectionAudit', { collection: 1, collectionId: 1, auditDate: -1 }, {});
function createMongoIndex(collection, collectionName: string, indexName: string, indexKeys: object, indexOptions?: object) {
if (Meteor.isServer) {
Meteor.wrapAsync(collection.rawCollection().indexInformation((err, indexInformation) => {
const stime=moment();
let dur;
if (err) {
if (err.message==="no collection") {
dur=moment().diff(stime, "ms");
consolewarn("Mongo Index]", collectionName, "- Does not exist (yet)", "took ["+dur+"ms]");
err=undefined;
return;
} else {
dur=moment().diff(stime, "ms");
consoleerror("[Mongo Index]", collectionName, "- FAIL to get index information for", collectionName, "took ["+dur+"ms]", err);
throw new Meteor.Error(err);
}
}
//consoledebug(indexInformation);
if (!indexInformation[indexName]) {
consolelog("[Mongo Index]", collectionName, "- Create a mongo index:", indexName);
indexOptions = indexOptions || {};
indexOptions['name'] = indexName;
Meteor.wrapAsync(collection.rawCollection().createIndex(indexKeys, indexOptions, (err2, indexName2) => {
if (err2) {
dur=moment().diff(stime, "ms");
consoleerror("[Mongo Index]", collectionName, "- FAIL", err2, "took ["+dur+"ms]");
throw new Meteor.Error(err2);
}
dur=moment().diff(stime, "ms");
consolelog("[Mongo Index]", collectionName, "- SUCCESS", indexName, "took ["+dur+"ms]");
}), collection.rawCollection());
} else {
dur=moment().diff(stime, "ms");
consoledebug("[Mongo Index]", collectionName, "- Using existing index:", indexName, "took ["+dur+"ms]");
}
}), collection.rawCollection());
}
}