Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
"Constraints" are rules for more in-depth checks performed at SQL level vs. at the Sequelize level. A typical example is checking that the email submitted is a unique email address. A user submits an entry, and their email gets checked against other emails in the database to ensure that it's unique.
Validation checks happen before any SQL is executed against the database. On the other hand, unique constraints (even allowNull
) map to their database counterparts.
Resources
Let's continue by adding a constraint for
our user model.
0:00
By constraints, I mean rules for
0:04
more in-depth checks performed at the SQL
level versus at the sequelize level.
0:06
For example, earlier we use
the notEmpty validator to ensure that
0:10
values don't get stored as empty strings.
0:14
And the isEmail validator
to check the email format.
0:17
As you learned,
if any of those validations fail,
0:21
a SQL query will not be
sent to the database.
0:24
However, with constraint checks
a SQL query is performed.
0:28
But if the constraint check fails,
the database throws an error
0:32
preventing the post or update, and
sequelize lets us know about it.
0:35
This is how constraint checks
differ from standard validation.
0:39
A common example is checking that the
email submitted is a unique email address.
0:42
A user submits an entry and their email
gets checked against other emails
0:48
in the database to
ensure that it's unique.
0:51
In the user model, I can define
a unique constraint on the email field
0:54
by adding the unique property to
the email object and setting it to true.
0:59
Back in Postman, I'll attempt to create
a new user entry using an email that
1:06
already exists in the users
table test@teamtreehouse.com.
1:11
When I press Send, I get a 400 status and
1:18
see the error email must
be unique in the response.
1:21
And notice in the console that the error
log is SequelizeUniqueConstrainError.
1:26
An attempt to insert an email
that already exists will throw
1:32
a SequeleUniqueConstraintError,
1:36
which prevents duplicate data from
being inserted into the database.
1:38
Like validators, we can customize
the error message for unique constraints.
1:44
Set the value of unique to an object,
1:49
inside the object use the message property
and set it to your custom message.
1:52
For example,
the email you entered already exists.
1:57
I'll test sending the same post request,
and this time I receive my
2:07
custom error message in the response.
Changing the email address
2:11
successfully creates and stores the new
user account in the database.
2:19
All right, I set up my one constraint for
unique user email addresses.
2:24
Next, I'll continue by adding
two more user model validations.
2:28
You need to sign up for Treehouse in order to download course files.
Sign up