Is it possible to create a unique pair in the mongo database?

Hello All,

I am using SimpleSchema and Collection2 from aldeed. I was wondering is there a way in Meteor or any of these packages to create a unique pairing? I want to create a record where the sender_user_id and receiver_user_id are unique in the collection, there will always only be one record with the same combo in the database. Is there a way to enforce this in mongo?

I am aware you can use “upsert” to get something like this but this is not what i am looking for.

Any info would be greatly appreciated

You can certainly enforce a unique index on a composite key (which I think is what you’re saying). In the server-side Meteor.startup():

MyCollection._ensureIndex({sender_user_id: 1, receiver_user_id: 1}, {unique: 1});

Note that this is an “underscore” method and so cannot be guaranteed to be present in future versions, but it’s been around for several years so far.

1 Like

Worked like a charm! Thank you!

1 Like

Hi @robfallows,

Is this method applicable/valid for value with different letter casing?

name: Bob Joe ,
name: bob joe

this should be invalid but in SS and collection2, it’s valid, the index and unique setting is only for exact letter casing.

What is the best approach on this.