Unique title

A common usecase is making sure we don't have duplicate names for our collection objects (eg. we don't want two teams called 'Manchester'). Collection2 supports this with the unique attribute. However it also wants us to create an index on our name attribute to speed up searching for names:

both/schemas/teams.js

Teams.attachSchema(new SimpleSchema({
  name: {
    type: String,
    index: true,
    unique: true
  },

  ownerId: {
    type: String
  },

  gameIds: {
    type: [String],
    optional: true
  }
}));

For those who don't know, an index makes it quicker to find documents by certain attributes. So now if we search for teams by name, it will be much faster (kind of like how a dictionary being sorted alphabetically makes it easier for us to look up a word).

Since we have specified we want our team names to be unique, Collection2 will now have to validate by searching through all the team names to make sure there are no duplications. This can be slow if we don't have an index.

Let's test this new rule by again running some commands in the browser console:

Teams.insert({name: 'Valencia', ownerId: Meteor.userId()})
Teams.insert({name: 'Valencia', ownerId: Meteor.userId()})

Trying to insert the same team twice now causes this error: insert failed: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: meteor.teams.$c2_name dup key: { : "Valencia" }. It seems it's working - great!