The Cloud Firestore ODM is currently in alpha. Expect breaking changes, API changes and more. The documentation is still a work in progress. See the discussion for more details.
A model represents exactly what data we expect to both receive and mutate on Firestore. The ODM ensures that all data is validated against a model, and if the model is not valid an error will be thrown.
To get started, assume we have a collection on our Firestore database called "Users". The collection contains many documents containing user information such as a name, age, email (and so on!). To define a model for this data, create a class:
User model defines that a user must have a name and email as a
String and age as an
Defining a model with standard Dart types (e.g.
int etc) works for many applications,
but what about more bespoke validation?
For example, a users age cannot be a negative value, so how do we validate against this?
The ODM provides some basic annotation validators which can be used on model properties. In this
example, we can take advantage of the
Min annotation ensures that any value for the
age property is always positive, otherwise an
error will be thrown.
To ensure validators are applied, the model instance is provided to the generated
method. Note the name of this class is generated based on the model name (for example a model named
Product with validators would generate a
The following annotations are available for
|Validates a number is not less than this value.|
|Validates a number is not greater than this value.|
In some cases, you may wish to validate data against custom validation. For example, we may want to
ensure the string value provided to
To define a custom validator, create a class which implements
Within the model, you can then apply the validator to the property:
On their own, a model does not do anything. Instead we create a "reference" using a model. A reference enables the ODM to interact with Firestore using the model.
To create a reference, we use the
Collection annotation which is used as a pointer to a collection
within the Firestore database. For example, the
users collection in the root of the database
corresponds to the
Users model we defined previously:
If you are looking to define a model as a reference on a Subcollection, read the Working with Subcollections documentation.
Some of the code on this page is created via code generation
UserCollectionReference) - you can learn more about
how to generate this code via the Code Generation documentation!