Ran into an issue where unique indexes were not being created.

In the Model definition, the attributes object contains a attribute identifier with a unique index. Looking at the MongoDB indexes list, it only shows _id.

attributes: {
    identifier: {
        type: 'string',
        unique: true,
        index: true
    }
}

In order to understand what was happening, we need to learn about the migrate attribute. This is from Sails documentation:

The migrate setting controls the auto-migration strategy that Sails will run every time your app loads. In short, this tells Sails whether or not you'd like it to attempt to automatically rebuild the tables/collections/sets/etc. in your database(s).

And further down the same page:

Even if all of your models use MongoDB, there are still some breaking schema changes to watch out for. For example, if you add unique: true to one of your attributes, a unique index must be created in MongoDB.

The possible values of migrate:

  • safe: Does nothing to the tables.
  • drop: Will delete all the tables and recreate them. Good for seeding new projects or testing setups.
  • alter: Makes changes to tables if models change, it tries to keep data but if it fails it will be deleted.

The issue turn out to be rather simple. When your migrate setting is set to safe Waterline will not attempt to create any indexes on the database, unique indexes are created on the database during a migration.

In a production environment you should migrate data manually, that includes creating indexes.