Bird
Raised Fist0
GCPcloud~10 mins

Firestore collections and documents in GCP - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Firestore collections and documents
Start
↓
Create Collection
↓
Add Document
↓
Document Contains Fields
↓
Add Subcollection?
Yes→Create Subcollection
↓
Add Document
↓
Read/Update/Delete Document
↓
End
This flow shows how you create a collection, add documents with fields, optionally add subcollections, and then read or modify documents.
Execution Sample
GCP
db.collection('users').doc('user1').set({name: 'Ana', age: 30})
This code creates a 'users' collection, adds a document with ID 'user1', and sets fields 'name' and 'age'.
Process Table
StepActionCollectionDocument IDFields AddedResult
1Create collection referenceusers--Reference to 'users' collection created
2Create document referenceusersuser1-Reference to document 'user1' created
3Set document fieldsusersuser1{name: 'Ana', age: 30}Document 'user1' created with fields
4Add subcollection reference?users/user1/orders--Subcollection 'orders' can be created under 'user1'
5Add document to subcollectionusers/user1/ordersorder1{item: 'book', qty: 1}Document 'order1' added to subcollection
6Read documentusersuser1-Fields returned: {name: 'Ana', age: 30}
7Update document fieldusersuser1{age: 31}Field 'age' updated to 31
8Delete documentusersuser1-Document 'user1' deleted
9Attempt to read deleted documentusersuser1-Document not found
10End---No more actions
💡 Execution stops after document deletion and failed read confirms removal.
Status Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 8After Step 9
users collectionemptycontains doc 'user1'contains doc 'user1' with subcollection 'orders'contains doc 'user1' with updated agedoc 'user1' deleteddoc 'user1' not found
user1 document fieldsnone{name: 'Ana', age: 30}{name: 'Ana', age: 30}{name: 'Ana', age: 31}deletednot found
orders subcollectionnonenonecontains doc 'order1'contains doc 'order1'contains doc 'order1'contains doc 'order1'
Key Moments - 3 Insights
Why does the document 'user1' still exist after adding a subcollection?
Adding a subcollection under 'user1' does not delete or replace the 'user1' document itself, as shown in steps 4 and 5 where 'user1' still has its fields.
What happens if you try to read a document after deleting it?
As seen in step 9, reading a deleted document returns 'Document not found' because the document no longer exists in the collection.
Can a collection exist without documents?
Yes, a collection reference can exist before any documents are added, as in step 1 where the 'users' collection is referenced but empty.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what fields does document 'user1' have after step 3?
A{name: 'Ana', age: 30}
B{item: 'book', qty: 1}
CNo fields, document is empty
DDocument deleted
💡 Hint
Check the 'Fields Added' column at step 3 in the execution table.
At which step does the 'age' field of 'user1' get updated?
AStep 3
BStep 7
CStep 5
DStep 9
💡 Hint
Look for the step where 'Update document field' action happens in the execution table.
If we delete the document 'user1' at step 8, what happens when we try to read it at step 9?
AReturns the original fields
BReturns updated fields
CReturns 'Document not found'
DReturns subcollection documents
💡 Hint
Check the 'Result' column at step 9 in the execution table.
Concept Snapshot
Firestore stores data in collections and documents.
Collections hold documents; documents hold fields.
Documents can have subcollections.
Create collection > add document with fields > optionally add subcollections.
Read, update, or delete documents anytime.
Deleting a document removes its fields but not necessarily its subcollections.
Full Transcript
Firestore organizes data in collections and documents. You start by creating a collection reference, then add documents identified by unique IDs. Each document holds fields, which are key-value pairs like name and age. Documents can also have subcollections, which are collections nested under a document. You can read, update, or delete documents. Deleting a document removes its fields and the document itself, but subcollections remain unless explicitly deleted. This flow helps manage structured data in Firestore efficiently.

Practice

(1/5)
1. What is the correct way to describe Firestore's data structure?
easy
A. Documents are the top-level containers holding collections.
B. Documents contain collections, and collections contain key-value pairs.
C. Collections contain key-value pairs directly without documents.
D. Collections contain documents, and documents contain key-value pairs.

Solution

  1. Step 1: Understand Firestore data hierarchy

    Firestore organizes data with collections at the top level, which hold documents.
  2. Step 2: Identify what documents contain

    Documents store data as key-value pairs, not collections directly.
  3. Final Answer:

    Collections contain documents, and documents contain key-value pairs. -> Option D
  4. Quick Check:

    Firestore data = collections > documents > key-value pairs [OK]
Hint: Remember: Collections hold documents, documents hold data [OK]
Common Mistakes:
  • Thinking documents hold collections directly
  • Assuming collections store key-value pairs without documents
  • Confusing the order of collections and documents
2. Which of the following is the correct syntax to get a reference to a document named user123 inside a collection users in Firestore using Node.js?
easy
A. const docRef = firestore.doc('user123/users');
B. const docRef = firestore.collection('users').doc('user123');
C. const docRef = firestore.collection('user123').doc('users');
D. const docRef = firestore.doc('users').doc('user123');

Solution

  1. Step 1: Identify correct method to access collection and document

    Use collection('users') to access the collection, then doc('user123') to get the document.
  2. Step 2: Check path correctness

    Direct firestore.doc(full/path) works for existing paths, but incorrect paths, reversed order, or misusing doc() on document references fail. Chaining collection().doc() is recommended.
  3. Final Answer:

    const docRef = firestore.collection('users').doc('user123'); -> Option B
  4. Quick Check:

    Use collection().doc() chaining for document refs [OK]
Hint: Chain collection() then doc() for document reference [OK]
Common Mistakes:
  • Swapping collection and document names
  • Using firestore.doc() with incorrect path format
  • Confusing collection() and doc() order
3. Given the following Firestore code snippet, what will be the output if the document user123 exists with fields {name: 'Alice', age: 30}?
const docRef = firestore.collection('users').doc('user123');
const docSnap = await docRef.get();
if (docSnap.exists) {
  console.log(docSnap.data());
} else {
  console.log('No such document!');
}
medium
A. 'No such document!'
B. undefined
C. { name: 'Alice', age: 30 }
D. Error: Document not found

Solution

  1. Step 1: Check if document exists

    The code checks docSnap.exists, which is true if the document is present.
  2. Step 2: Output document data

    If exists, docSnap.data() returns the document fields as an object.
  3. Final Answer:

    { name: 'Alice', age: 30 } -> Option C
  4. Quick Check:

    docSnap.exists true means data() returns fields [OK]
Hint: docSnap.exists true means data() returns document fields [OK]
Common Mistakes:
  • Assuming data() returns undefined if document exists
  • Confusing exists check with data presence
  • Expecting error instead of 'No such document!' message
4. You wrote this Firestore code to get a document but docSnap.exists is false:
const docRef = firestore.collection('users').doc();
const docSnap = await docRef.get();
What is the problem?
medium
A. Missing document ID in doc() causes a reference to a non-existing document.
B. You cannot call get() on a document reference.
C. Collection name 'users' is invalid without quotes.
D. You must use firestore.doc() instead of collection().doc().

Solution

  1. Step 1: Check doc() usage

    Calling doc() without an ID creates a reference to a new document with an auto-generated ID, but it does not exist yet.
  2. Step 2: Understand get() on new doc reference

    Trying to get() returns a snapshot with exists=false because the document does not exist.
  3. Final Answer:

    Missing document ID in doc() causes a reference to a non-existing document. -> Option A
  4. Quick Check:

    doc() needs ID to get existing document [OK]
Hint: Always provide document ID in doc() to read existing document [OK]
Common Mistakes:
  • Assuming doc() without ID points to existing document
  • Thinking get() cannot be called on document references
  • Confusing collection and document method usage
5. You want to store user profiles in Firestore where each user has multiple addresses. Which is the best Firestore structure to model this data?
hard
A. A collection 'users' with documents for each user, and each user document has a subcollection 'addresses' with address documents.
B. A single collection 'addresses' with documents containing user info and address fields combined.
C. A collection 'users' where each document stores all addresses as a large array field.
D. Multiple collections named after each user ID, each containing address documents.

Solution

  1. Step 1: Understand Firestore best practice for one-to-many

    Use a main collection for users, and subcollections for related multiple items like addresses.
  2. Step 2: Evaluate options

    A collection 'users' with documents for each user, and each user document has a subcollection 'addresses' with address documents. uses subcollections for addresses, which is scalable and organized. A single collection 'addresses' with documents containing user info and address fields combined. mixes user and address data in one collection, which is less clear. A collection 'users' where each document stores all addresses as a large array field. stores all addresses in one field, which can be inefficient. Multiple collections named after each user ID, each containing address documents. creates many collections dynamically, which is not recommended.
  3. Final Answer:

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

    Use subcollections for related multiple items [OK]
Hint: Use subcollections for multiple related documents per user [OK]
Common Mistakes:
  • Storing multiple addresses in one array field causing size limits
  • Creating dynamic collections per user causing management issues
  • Mixing unrelated data in one collection
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