Auto-migrations settings
unique
Summary
By default, Sails does not enforce uniqueness for attributes like email. If you create multiple records with the same email, they will be accepted unless explicitly prevented. To enforce uniqueness, you need to set the unique
property to true
in the model definition. This ensures that Sails creates a unique index at the database level, preventing duplicate entries.
Once this is set, any attempt to insert a duplicate value will result in an AdapterError, indicating a violation of the uniqueness constraint. This is useful for fields like emails, usernames, or any attribute that must be unique per record.
Transcript
In your model, you might need unique attributes—fields that should have only one value per record. A common example is email.
Let’s say we define an email
attribute like this:
attributes: {
email: {
type: 'string'
}
}
If we now create two records with the same email:
await User.create({ email: 'koo@example.com' });
await User.create({ email: 'koo@example.com' });
Sails allows this by default. Checking the database, we see both records exist, which isn't what we want. Looking at the indexes, we see that only the id
field is marked as unique.
Enforcing Uniqueness
To enforce uniqueness, we modify the attribute:
attributes: {
email: {
type: 'string',
unique: true
}
}
When Sails creates the table, it will also create a unique index on the email
field. Running a migration and checking the database structure now shows that email
is indexed as unique.
Now, if we try to create two records with the same email, the first will be created successfully, but the second will throw an AdapterError:
AdapterError: A record already exists with conflicting values.
This ensures that every user has a unique email. You can apply this to other fields like username
or any attribute that should be unique across records.
Full Course
USD