0
0
Firebasecloud~5 mins

Subcollections in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you want to organize your data in groups inside other groups. Subcollections let you keep related data inside a main group, like folders inside folders. This helps keep your data neat and easy to find.
When you want to store comments inside a specific blog post document.
When you need to keep user orders inside each user’s profile document.
When you want to group messages inside a chat room document.
When you want to separate settings for each project inside the project document.
When you want to keep logs or history inside a main record without mixing with other data.
Commands
This command creates a main document for a user with ID user123 in the users collection. It sets up the main group where subcollections can be added.
Terminal
firebase firestore:documents:create users/user123
Expected OutputExpected
Document users/user123 created successfully.
This command creates a subcollection document order001 inside the orders subcollection of the user123 document. It shows how to add a nested group inside the main group.
Terminal
firebase firestore:documents:create users/user123/orders/order001
Expected OutputExpected
Document users/user123/orders/order001 created successfully.
This command retrieves the subcollection document order001 inside the orders subcollection of user123. It verifies that the nested document exists and can be accessed.
Terminal
firebase firestore:documents:get users/user123/orders/order001
Expected OutputExpected
{ "name": "projects/{projectId}/databases/(default)/documents/users/user123/orders/order001", "fields": {} }
Key Concept

If you remember nothing else from this pattern, remember: subcollections let you organize data inside documents like folders inside folders for clear structure.

Common Mistakes
Trying to create a subcollection without first creating the parent document.
Subcollections must be inside an existing document; if the parent document does not exist, the subcollection cannot be created.
Always create the main document first before adding subcollections inside it.
Using the same collection name at different levels without clear structure.
This can cause confusion and make it hard to find data because collections with the same name at different levels look similar.
Use clear and distinct collection names to keep your data easy to navigate.
Summary
Create a main document first to hold your data group.
Add subcollections inside the main document to organize related data.
Use commands to create and verify documents and subcollections step-by-step.