Skip to main content

Working with Subcollections

Notice

This page is archived and might not reflect the latest version of the FlutterFire plugins. You can find the latest information on GitHub:

https://github.com/firebase/flutterfire/tree/master/packages/cloud_firestore_odm

Alpha Status

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.

The ODM provides support for subcollections via the Collection annotation. For example, first define the root collection as normal:

@JsonSerializable(explicitToJson: true)
class User {
// ...
}
@Collection<User>('users')
final usersRef = UserCollectionReference();

Let's assume each user document contains a subcollection containing user addresses. Firstly define the model for an address:

@JsonSerializable(explicitToJson: true)
class Address {
// ...
}

Next, define the path to the subcollection in a new Collection annotation:

@Collection<User>('users')
@Collection<Address>('users/*/addresses')
final usersRef = UserCollectionReference();

After code generation, we can now access the sub-collection via the usersRef reference:

AddressCollectionReference addressesRef = usersRef.doc('myDocumentID').addresses;

The subcollection reference has full access to the same functionality as root collections. To learn more about usage of references, see the using references documentation.