Check out v4 of the Fauna CLI
v4 of the Fauna CLI is now in beta. The new version introduces enhancements to the developer experience, including an improved authentication workflow. To get started, check out the CLI v4 quick start. |
FSL collection schema: Unique constraint definitions
Learn: Unique constraints |
---|
A unique constraint ensures a field value or combination of field values is unique for each document in a collection. Fauna rejects document writes that don’t meet the constraint.
You define unique constraints as part of an FSL collection schema:
collection Customer {
...
// Unique constraint.
// Ensures a field value or combination of field values
// is unique for each document in the collection.
// Supports multivalue attribute (`mva`) fields, such as Arrays.
unique [.name, .description, mva(.categories)]
...
}
You can create and manage schema using any of the following:
-
The Fauna CLI
-
The Fauna Dashboard
-
The Fauna Core HTTP API’s Schema endpoints
Fauna stores each collection schema as an FQL document in the
Collection
system collection. The Collection
document’s constraints
field contains FQL
versions of the collection’s unique constraint definitions.
Discussion
Unique constraints are applied when a new document is created or when an existing document is updated. Constraints aren’t applied retroactively to existing documents.
You can declare any number of constraints that define which Document fields must have unique values in the Collection. For example:
collection Customer {
...
unique [.email]
unique [.firstName, .lastName]
...
}
A unique constraint can define multiple fields that must be unique in
combination. If the firstName
and lastName
fields in the example are
defined as a unique constraint, the first and last name combination must be
unique for the collection.
If you create a unique constraint over more than one field, the absence of
one or more fields with the presence of other fields in the unique constraint
is a combination that the constraint is enforced over. In the first and last
name example, if you create a user and populate only the lastName
field,
you can’t create another user with only the same last name, but you can create
another user with the same last name if you also define a firstName
field.
When one or more fields are part of a unique constraint, multiple documents can’t have the same combination of values for the constrained fields.
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!