Bird
Raised Fist0
Firebasecloud~5 mins

Document-collection data model in Firebase - Commands & Configuration

Choose your learning style10 modes available
Introduction
When you store data in Firebase Firestore, you organize it in documents and collections. This helps keep your data neat and easy to find, like folders and files on your computer.
When you want to save user profiles with different details for each user.
When you need to store messages in a chat app, grouped by conversation.
When you want to keep track of products in an online store, each with its own info.
When you want to organize blog posts and their comments separately.
When you want to quickly find data by grouping related items together.
Config File - firestore.rules
firestore.rules
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

This file sets simple rules allowing anyone to read and write data in Firestore. It is used here to let you test the document-collection model without permission issues. In real apps, you should secure your data with proper rules.

Commands
This command creates a document named 'user123' inside the 'users' collection with fields 'name' and 'age'. It shows how to add a single document.
Terminal
firebase firestore:documents:create users/user123 '{"name": "Alice", "age": 30}'
Expected OutputExpected
Document users/user123 created successfully.
This command retrieves the document 'user123' from the 'users' collection to verify it was saved correctly.
Terminal
firebase firestore:documents:get users/user123
Expected OutputExpected
{ "name": "Alice", "age": 30 }
This command creates a subcollection 'orders' under the document 'user123' and adds a document 'order001' with order details. It shows nested collections.
Terminal
firebase firestore:documents:create users/user123/orders/order001 '{"item": "book", "price": 15}'
Expected OutputExpected
Document users/user123/orders/order001 created successfully.
This command retrieves the order document to confirm the nested data was saved.
Terminal
firebase firestore:documents:get users/user123/orders/order001
Expected OutputExpected
{ "item": "book", "price": 15 }
Key Concept

If you remember nothing else from this pattern, remember: Firestore stores data in documents inside collections, and documents can have nested collections for organized, flexible data.

Common Mistakes
Trying to create a document without specifying the full path including collection and document IDs.
Firestore requires a collection and document ID to know where to store the data.
Always specify the full path like 'collection/document' when creating or accessing documents.
Storing large amounts of data in a single document instead of using collections and subcollections.
Documents have size limits and can become slow to read or update if too large.
Split data into multiple documents inside collections to keep each document small and fast.
Summary
Use collections to group related documents, like folders holding files.
Create documents with unique IDs inside collections to store data records.
Documents can have subcollections for nested, organized data.
Use commands to create and retrieve documents to manage your Firestore data.

Practice

(1/5)
1. In Firebase's document-collection data model, what is the main container that holds documents?
easy
A. A collection
B. A table
C. A row
D. A field

Solution

  1. Step 1: Understand Firebase data structure

    Firebase stores data in documents, and these documents are grouped inside collections.
  2. Step 2: Identify the container for documents

    The container that holds multiple documents is called a collection, not a table, row, or field.
  3. Final Answer:

    A collection -> Option A
  4. Quick Check:

    Documents are inside collections [OK]
Hint: Remember: collections hold documents, like folders hold files [OK]
Common Mistakes:
  • Confusing collections with tables from SQL
  • Thinking documents are inside fields
  • Mixing up rows with documents
2. Which of the following is the correct way to reference a document named user123 inside a collection users in Firebase?
easy
A. db.collection('users').doc('user123')
B. db.doc('users').doc('user123')
C. db.collection('user123').doc('users')
D. db.users('user123')

Solution

  1. Step 1: Recall Firebase syntax for document reference

    To get a document inside a collection, use collection('name').doc('id').
  2. Step 2: Match the correct syntax

    db.collection('users').doc('user123') uses db.collection('users').doc('user123'), which is the standard way.
  3. Final Answer:

    db.collection('users').doc('user123') -> Option A
  4. Quick Check:

    Use collection then doc to reference documents [OK]
Hint: Use collection('name').doc('id') to get a document [OK]
Common Mistakes:
  • Swapping collection and doc order
  • Using dot notation like db.users('user123')
  • Using doc with full path incorrectly
3. Given this code snippet in Firebase:
const docRef = db.collection('books').doc('book1');
await docRef.set({ title: 'Learn Firebase', pages: 150 });
const snapshot = await db.collection('books').get();
const titles = snapshot.docs.map(doc => doc.data().title);
console.log(titles);
What will be printed in the console if the 'books' collection was empty before?
medium
A. []
B. ['book1']
C. ['Learn Firebase']
D. Error: Cannot read property 'title' of undefined

Solution

  1. Step 1: Understand the code flow

    The code adds a document 'book1' with title and pages to 'books' collection, then fetches all documents in 'books'.
  2. Step 2: Analyze the output of mapping titles

    Since 'books' was empty before, after adding 'book1', the collection has one document with title 'Learn Firebase'. Mapping titles returns ['Learn Firebase'].
  3. Final Answer:

    ['Learn Firebase'] -> Option C
  4. Quick Check:

    Added one doc, so titles list has one title [OK]
Hint: After set(), collection has that document; map titles returns it [OK]
Common Mistakes:
  • Thinking snapshot is empty before set()
  • Confusing document ID with title
  • Expecting error due to async code
4. Consider this Firebase code snippet:
const userRef = db.collection('users').doc('user1');
userRef.get().then(doc => {
  if (doc.exists) {
    console.log(doc.data().name);
  } else {
    console.log('No such document!');
  }
});
If the document 'user1' does not exist, what will be printed?
medium
A. undefined
B. 'No such document!'
C. Error: doc.data() is undefined
D. null

Solution

  1. Step 1: Check the existence condition

    The code checks if doc.exists is true before accessing data.
  2. Step 2: Understand behavior when document missing

    If the document does not exist, doc.exists is false, so it prints 'No such document!'.
  3. Final Answer:

    'No such document!' -> Option B
  4. Quick Check:

    doc.exists false triggers else block [OK]
Hint: Check doc.exists before accessing data to avoid errors [OK]
Common Mistakes:
  • Trying to access data without checking doc.exists
  • Expecting undefined or null instead of message
  • Confusing doc.exists with doc.data()
5. You want to store a list of users, each with multiple addresses, in Firebase. Which data model best fits this scenario?
hard
A. One document 'users' containing all users and their addresses as nested arrays
B. A single collection 'addresses' with documents containing user info and address combined
C. Multiple collections named after each user containing address documents
D. A collection 'users' with documents for each user, each containing a subcollection 'addresses' with address documents

Solution

  1. Step 1: Understand hierarchical data in Firebase

    Firebase supports subcollections inside documents, which is ideal for related nested data.
  2. Step 2: Choose the best structure for users and their multiple addresses

    Using a 'users' collection with each user document having an 'addresses' subcollection keeps data organized and scalable.
  3. Final Answer:

    A collection 'users' with documents for each user, each containing a subcollection 'addresses' with address documents -> Option D
  4. Quick Check:

    Use subcollections for nested related data [OK]
Hint: Use subcollections for nested lists like addresses per user [OK]
Common Mistakes:
  • Storing all users and addresses in one big document
  • Mixing user and address data in one collection without hierarchy
  • Creating many collections named after users
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