How to define the CollectionReference of a subcollection with the JS SDK V9?
I often see some questions on StackOverflow on how to define the CollectionReference
corresponding to a subcollection, when using the JavaScript SDK Version 9.
IMO, the main reason for questions on this subject is that the official Firebase documentation does not show any example (at the time of writing this short article).
In the “Subcollections” section of the documentation (see above link) we do find a code example, but it shows how to define the DocumentReference
of a document in a subcollection, and not how to define the CollectionReference
corresponding to the parent subcollection of this document.
So, how to do that?
Let’s first look at the API reference documentation for the collection()
method of the JavaScript SDK V9:
The signature of the method is as follows:
export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference<DocumentData>;
The methods take two to three parameters:
- The first parameter is a reference to the root
Firestore
instance, but can also be aCollectionReference
(see the below examples); - The second parameter is the path of the collection, i.e. a slash-separated String representing the path of the subcollection;
- The last parameter is optional, and since it is defined by using the spread operator, it can be any number of additional path segments. The only constraint is that the (sub)collection must have an odd number of path segments.
Let see that with concrete examples:
And that’s it. Thanks for reading.