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.

The values are evaluated when validating document Collection.create() and update() requests.

You include unique constraints in a collection schema.

Syntax

unique [<constraintTerm> . . .]

Members

Member Type Required Description

constraintTerm

String

Yes

Document field to constrained to a unique value. + Use mva() to constrain every element of an Array field.

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]
  ...
}

In the example, the username must be unique in the collection.

A unique constraint can define multiple fields that must be unique in combination. If the name.first and name.last 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 name.last 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 name.first 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.

Examples

unique [.creditCard.number]

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!