Removing index from collection in meteor

I would like to remove an index of an collection (in my meteor app) if it is existing. I’m doing this in a method.

if (Meteor.isServer)
	Collection._dropIndex('c2_slug');	

This gives me the error

Exception while invoking method 'update' MongoError: invalid index name spec

So, how can I check in via meteor if the index is existing?
An alternative solution would be to remove all existing indexes (except _id), but Collection.dropIndexes() is failing with Collection.dropIndexes is not a function

I wrote a test for grapher for something similar, maybe it will help you:

    it ('Should have indexes set up', function () {
        const raw = PostCollection.rawCollection();
        const indexes = Meteor.wrapAsync(raw.indexes, raw)();

        const found = _.find(indexes, index => {
            return index.key.commentIds == 1;
        });

        assert.isObject(found);
    });

I think this is something different, as I’m thinking of collection indexes…

This is an old thread but I was looking into that recently.

@diaconutheodor’s reply is relevant to what you’re asking as it gives you a recipe to find all the names and keys of all indexes in a Collection.

Check the relevant mongo documentation on how an index’s name is different from the respective field name in your collection.

An alternative recipe to @diaconutheodor’s would be:
Start a meteor shell on your server and run something similar to:

> const c = MyCollection.rawCollection(); 
> c.indexes((err, res)=>{console.log(res)}

Then check your server log/terminal window and you should see a list of all the indexes for the specific collection.
Notice that the list should include one key and one name parameter for each index entry. You can use either of those values in _dropIndex in order to drop the specific index. e.g.

MyCollection._dropIndex( "indexName" ) or

MyCollection._dropIndex( { "indexKey": -1 } )

This is not the best answer, but I think it’s good for simple use.

Index name is not just a name when we give _ensureIndex ‘indexName’
It’s like indexName_1 something like this.
The naming rule is same as I know, before encountered to the same rules again.
You could see that on MongoDB Client tools such as Robo 3T or by such code above.

And you should use try catch statement to avoid ‘attempt drop not exist index’.
_ensureIndex makes ‘ensure’ the index so nothing happend when the index founded,
but _dropIndex throw exception when the index not founded.

so just ignore that exception works enough for me to manage index by code.

<coffeescript>

try Collection._dropIndex 'indexName_1' 

No exception handling needed cause I just wanted make sure Indexes when the project run.

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