Bird
Raised Fist0
Firebasecloud~10 mins

Subcollections in Firebase - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Subcollections
Start: Access Root Collection
↓
Select Document in Root
↓
Access Subcollection inside Document
↓
Perform Operation (Read/Write) on Subcollection Document
↓
End
Access starts at a root collection, then a document inside it, then a subcollection inside that document, where operations happen.
Execution Sample
Firebase
db.collection('users').doc('user1').collection('orders').doc('order1').get()
This code reads the document 'order1' inside the 'orders' subcollection of the 'user1' document in the 'users' collection.
Process Table
StepActionTargetResult
1Access collection'users'Reference to 'users' collection
2Select document'user1'Reference to 'user1' document
3Access subcollection'orders'Reference to 'orders' subcollection inside 'user1'
4Select document'order1'Reference to 'order1' document inside 'orders'
5Get document data'order1'Returns data of 'order1' document
6EndN/AOperation complete
💡 Operation ends after retrieving the 'order1' document data from the subcollection.
Status Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
dbRefFirebase DB rootusers collection refuser1 doc reforders subcollection reforder1 doc reforder1 doc dataorder1 doc data
Key Moments - 2 Insights
Why do we need to select a document before accessing a subcollection?
Because subcollections belong inside specific documents, you must first select the document to reach its subcollection, as shown in steps 2 and 3 of the execution_table.
Can we access a subcollection directly without specifying the parent document?
No, subcollections are nested inside documents, so you must specify the parent document first (step 2) before accessing the subcollection (step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the target at step 3?
A'user1' document inside 'users' collection
B'order1' document inside 'orders' subcollection
C'orders' subcollection inside 'user1' document
D'users' collection
💡 Hint
Refer to the 'Target' column in row for step 3 in execution_table.
At which step do we get the actual data of the 'order1' document?
AStep 5
BStep 4
CStep 2
DStep 3
💡 Hint
Check the 'Action' and 'Result' columns in execution_table for when data is retrieved.
If we skip step 2 and try to access 'orders' subcollection directly, what happens?
AWe get a reference to 'orders' subcollection of the root
BError or invalid reference because subcollections need a parent document
CWe access all 'orders' subcollections in the database
DWe get the 'orders' collection at root level
💡 Hint
Recall key_moments about needing to select a document before subcollection.
Concept Snapshot
Subcollections are collections inside documents.
Access flow: collection -> document -> subcollection -> document.
You must specify the parent document before accessing its subcollection.
Operations on subcollections are like normal collections but nested.
Useful for organizing related data hierarchically.
Full Transcript
Subcollections in Firebase are collections nested inside documents. To access data in a subcollection, you first select the root collection, then the specific document inside it, then the subcollection inside that document, and finally the document inside the subcollection. For example, to get an order of a user, you access 'users' collection, then 'user1' document, then 'orders' subcollection, then 'order1' document. This nested structure helps organize data logically. You cannot access a subcollection without specifying its parent document first. The execution steps show how references move from root collection down to the subcollection document, and finally retrieve the data. This step-by-step access ensures data is well organized and queries are precise.

Practice

(1/5)
1. What is a subcollection in Firebase Firestore?
easy
A. A backup copy of a collection stored in another region
B. A special type of document that stores user credentials
C. A collection nested inside a document to organize related data
D. A collection that automatically deletes old documents

Solution

  1. Step 1: Understand Firestore data structure

    Firestore stores data in collections and documents. Documents can contain subcollections.
  2. Step 2: Define subcollection purpose

    A subcollection is a collection inside a document used to organize related data hierarchically.
  3. Final Answer:

    A collection nested inside a document to organize related data -> Option C
  4. Quick Check:

    Subcollection = nested collection inside document [OK]
Hint: Subcollections are collections inside documents [OK]
Common Mistakes:
  • Thinking subcollections are special documents
  • Confusing subcollections with backups
  • Assuming subcollections auto-delete data
2. Which of the following is the correct way to access a subcollection named comments inside a document with ID post1 in the posts collection?
easy
A. db.collection('comments').doc('post1').collection('posts')
B. db.collection('posts').collection('post1').doc('comments')
C. db.doc('posts/post1/comments')
D. db.collection('posts').doc('post1').collection('comments')

Solution

  1. Step 1: Identify the correct chaining method

    To access a subcollection, first get the parent collection, then the document, then the subcollection.
  2. Step 2: Match the correct syntax

    db.collection('posts').doc('post1').collection('comments') correctly chains collection('posts'), doc('post1'), then collection('comments').
  3. Final Answer:

    db.collection('posts').doc('post1').collection('comments') -> Option D
  4. Quick Check:

    Access subcollection by chaining collection, doc, collection [OK]
Hint: Chain collection, doc, then subcollection to access nested data [OK]
Common Mistakes:
  • Swapping doc and collection order
  • Using doc() instead of collection() for subcollections
  • Trying to access subcollection directly without parent doc
3. Given the following code snippet, what will console.log(snapshot.docs.length) output if the comments subcollection has 3 documents?
const commentsRef = db.collection('posts').doc('post1').collection('comments');
const snapshot = await commentsRef.get();
console.log(snapshot.docs.length);
medium
A. 3
B. 1
C. 0
D. undefined

Solution

  1. Step 1: Understand what get() returns

    The get() method on a collection reference returns a snapshot containing all documents in that collection.
  2. Step 2: Count documents in the snapshot

    snapshot.docs.length gives the number of documents retrieved, which is 3 as stated.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Docs count in subcollection = 3 [OK]
Hint: snapshot.docs.length shows number of documents fetched [OK]
Common Mistakes:
  • Assuming get() returns a single document
  • Confusing docs.length with data length
  • Expecting undefined if subcollection exists
4. You wrote this code to add a comment to a post's subcollection but it throws an error:
const commentRef = db.collection('posts').collection('post1').collection('comments').doc();
await commentRef.set({ text: 'Nice post!' });
What is the error in this code?
medium
A. Using collection('post1') instead of doc('post1') to access the post document
B. Missing await keyword before set()
C. doc() requires an ID argument
D. Cannot add documents to subcollections

Solution

  1. Step 1: Check the chaining of collection and doc

    Subcollections must be accessed by first selecting the parent document with doc('post1'), not collection('post1').
  2. Step 2: Identify the incorrect method call

    Using collection('post1') treats 'post1' as a collection, causing an error.
  3. Final Answer:

    Using collection('post1') instead of doc('post1') to access the post document -> Option A
  4. Quick Check:

    Access document with doc(), not collection() [OK]
Hint: Use doc() for documents, collection() for collections [OK]
Common Mistakes:
  • Confusing collection() and doc() methods
  • Assuming doc() always needs an ID
  • Thinking subcollections can't have new documents
5. You want to model a blog where each post has multiple comments stored as a subcollection. Which approach is best to keep your Firestore database scalable and organized?
hard
A. Store all comments in a single top-level collection named 'comments' with a postId field
B. Store comments as a subcollection inside each post document
C. Store comments inside the post document as an array field
D. Create a separate Firestore database for comments

Solution

  1. Step 1: Consider Firestore best practices for related data

    Storing comments as a subcollection inside each post keeps related data grouped and queries efficient.
  2. Step 2: Evaluate other options

    Store all comments in a single top-level collection named 'comments' with a postId field can cause large collections and complex queries; Store comments inside the post document as an array field risks document size limits; Create a separate Firestore database for comments is unnecessary complexity.
  3. Final Answer:

    Store comments as a subcollection inside each post document -> Option B
  4. Quick Check:

    Subcollections keep related data organized and scalable [OK]
Hint: Use subcollections for related lists to keep data organized [OK]
Common Mistakes:
  • Putting large arrays inside documents risking size limits
  • Using one big collection causing slow queries
  • Creating multiple databases unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard