Firebase Subcollections
Before we talk about subcollections in Firebase Firestore let us go over how Firestore works. Firestore is a NoSQL document oriented database. There are no tables. Instead everything is stored in documents, which in turn is organized into collections. There is no schema, so technically you can customize each document however you like. But it is good practice to keep the same fields and data types across multiple documents, so that you can query the documents more easily.
While collections can only hold documents, documents can hold a variety of data types including boolean, number, string, array, map, geo point, binary blob, and timestamp. Documents are lightweight JSON records.
Here is where subcollections come in.
Subcollections
Within a document you can create a new collection which in turn can only hold documents. You can keep creating these subcollections up to 100 levels deep. The way to access these subcollections is by going through the document.
const example = db.collection('colName1').doc('docName1')
.collection('subColName1').doc('subDocName1');
You cannot reference a collection in a collection or a document in a document.
Pros
- You can create collections within documents when you have data that might expand over time.
If you believe that your data will grow tremendously, the parent document won’t change in size; helping to keep things organized (imagine every time someone leaves a comment or a like there is a write to your database with a new document).
Use case would be a chat app. Depending on how you would like to structure your app; you could have code as follows:
collection(‘rooms’).doc('roomA').collection('messages').doc('message1')
2. Collection Group Queries - You can query multiple collections that have the same subcollection name. Ie they are part of the same Collection Group.
This advantage is very useful for doing queries. Instead of having to do separate queries to get the information you want, you only need to do one.
Use cases would be an app such as Yelp that reviews restaurants:
collection('restaurants').doc('nameOfRestaurant1').collection('reviews').doc('review1')
You would only need to do one query to get all the reviews for all the restaurants!
Note: Before you start doing a Collection Group Query you first need to create an index that supports it.
Cons
- You can’t easily delete a subcollection.
You need to manually delete each subcollection. Fortunately you can write a callable cloud function to do it for you. - Deleting a document does not delete its subcollection!
This is really part of number one but a different aspect of it. This means that you are unable to query any of those subcollections but can still access them through the Firebase Console. If your intention was to delete everything refer back to number one.
I hope this gives you some understanding of what Firebase Firestore subcollections are and gives you some insight into designing your database. Happy Coding!