Bird
Raised Fist0
Firebasecloud~20 mins

Subcollections in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Subcollections Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Understanding Firestore Subcollections Structure

In Firestore, you have a collection named users. Each user document has a subcollection called orders. What is the correct path to access the orders subcollection for a user with ID user123?

Aorders/users/user123
Busers/user123/orders
Cusers/orders/user123
Dorders/user123/users
Attempts:
2 left
💡 Hint

Think about the hierarchy: collection > document > subcollection.

❓ Architecture
intermediate
2:00remaining
Best Practice for Storing User Messages in Firestore

You want to store messages sent by users in a Firestore database. Each user can have many messages. Which design uses subcollections correctly and scales well?

ACreate a <code>messages</code> collection with documents named by user ID, each containing all messages as fields.
BCreate a single <code>messages</code> collection with all messages, each document containing a user ID field.
CCreate a <code>users</code> collection, each user document has a <code>messages</code> subcollection with individual message documents.
DStore all messages in a single document inside <code>users</code> collection under a <code>messages</code> field as an array.
Attempts:
2 left
💡 Hint

Consider how Firestore handles large arrays and document size limits.

❓ Configuration
advanced
2:00remaining
Firestore Security Rules for Subcollections

You want to write Firestore security rules to allow users to read and write only their own orders subcollection documents. Which rule snippet correctly enforces this?

Firebase
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/orders/{orderId} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
Arequest.auth.uid == userId
Brequest.auth.token.email == userId
Crequest.auth.uid != userId
Drequest.auth.token.admin == true
Attempts:
2 left
💡 Hint

Check how to compare authenticated user ID with document path variable.

❓ service_behavior
advanced
2:00remaining
Query Behavior on Firestore Subcollections

You run this query in Firestore:

db.collectionGroup('orders').where('status', '==', 'shipped').get()

What does this query return?

AOnly documents in the <code>orders</code> subcollection of the root collection.
BAn error because <code>collectionGroup</code> cannot be used with subcollections.
CDocuments in the <code>orders</code> subcollection of the first user document only.
DAll documents in all <code>orders</code> subcollections across the database with status 'shipped'.
Attempts:
2 left
💡 Hint

Think about what collectionGroup queries do.

❓ security
expert
3:00remaining
Preventing Unauthorized Access to Nested Subcollections

You have a Firestore database with users collection. Each user document has a projects subcollection, and each project document has a tasks subcollection. You want to ensure users can only read and write tasks in their own projects. Which security rule snippet correctly enforces this?

Firebase
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/projects/{projectId}/tasks/{taskId} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}
Arequest.auth.uid == userId
Brequest.auth.uid == projectId
Crequest.auth.token.email == userId
Drequest.auth.uid == taskId
Attempts:
2 left
💡 Hint

Remember the user ID is in the document path, not project or task IDs.

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