Creating unique indexes on Mongo.Collections

I’d like to have a unique key in one of my collections. SimpleSchema has a way to specify this, but I’ve decided (for now at least) not to use SimpleSchema. What might be another way of having a unique index?

I was thinking I could just do something like this on the server-side, in the file that defines the collection (which runs on both client and server):

if (Meteor.isServer) {
    collection.rawCollection().createIndex({ someKey: 1 }, { unique: true })
}

and then maybe I can catch that error somehow.

if (Meteor.isServer) {
    SomeCollection._ensureIndex({ someKey: 1, compoundOtherKey: 1 }, { unique: true })
}

is the canonical way in Meteor.

The problem is catching the error because the mongodb messages are not exactly very helpful.

Take a look at how collection2 does it to take some cue:

https://github.com/aldeed/meteor-collection2/blob/master/lib/collection2.js#L352

2 Likes