Bird
Raised Fist0
Firebasecloud~20 mins

Getting a single document in Firebase - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Firestore Document Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ service_behavior
intermediate
2:00remaining
What is the output of this Firebase Firestore code snippet?

Consider the following Firebase Firestore code to get a single document by ID:

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!');
}

What will be printed if the document with ID 'user123' exists and contains {name: 'Alice', age: 30}?

Firebase
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!');
}
Anull
B"No such document!"
Cundefined
D{name: 'Alice', age: 30}
Attempts:
2 left
💡 Hint

Check what docSnap.data() returns when the document exists.

🧠 Conceptual
intermediate
1:30remaining
Which Firebase method retrieves a single document by its ID?

You want to get a single document from a Firestore collection by its ID. Which method should you use?

Acollection('users').doc('user123').get()
Bcollection('users').get()
Ccollection('users').where('id', '==', 'user123').get()
Dcollection('users').add({id: 'user123'})
Attempts:
2 left
💡 Hint

Think about how to directly access a document by its ID.

❓ security
advanced
2:00remaining
What happens if Firestore security rules deny read access to a document you try to get?

You run this code to get a document:

const docSnap = await firestore.collection('users').doc('user123').get();

But your Firestore security rules deny read access to this document for your user. What will happen?

AThe get() call returns null without error.
BThe get() call returns an empty object {}.
CThe get() call throws a permission error and the document is not returned.
DThe get() call returns the document data but logs a warning.
Attempts:
2 left
💡 Hint

Consider how Firestore enforces security rules on reads.

❓ Configuration
advanced
2:30remaining
Which code snippet correctly handles the case when a Firestore document does not exist?

You want to get a document and handle the case where it might not exist. Which snippet correctly does this?

A
const docSnap = await firestore.collection('users').doc('user123').get();
if (docSnap === null) {
  console.log('Document missing');
} else {
  console.log(docSnap.data());
}
B
const docSnap = await firestore.collection('users').doc('user123').get();
if (!docSnap.exists) {
  console.log('Document missing');
} else {
  console.log(docSnap.data());
}
C
const docSnap = await firestore.collection('users').doc('user123').get();
if (docSnap.data() === null) {
  console.log('Document missing');
} else {
  console.log(docSnap.data());
}
D
const docSnap = await firestore.collection('users').doc('user123').get();
if (docSnap.data() === undefined) {
  console.log('Document missing');
} else {
  console.log(docSnap.data());
}
Attempts:
2 left
💡 Hint

Check the property that indicates document existence.

❓ Architecture
expert
3:00remaining
In a large app, which approach best optimizes reading a single Firestore document frequently?

You have a Firestore document that your app reads very often. Which approach best optimizes performance and cost?

AUse Firestore's offline persistence and cache the document locally to reduce reads.
BCall get() on the document every time you need it to ensure fresh data.
CUse a Cloud Function to read the document and send it to the client on every request.
DDuplicate the document data in Realtime Database for faster reads.
Attempts:
2 left
💡 Hint

Think about caching and offline capabilities Firestore offers.

Practice

(1/5)
1. What does the getDoc() function do in Firebase when working with a single document?
easy
A. It fetches the data of a specific document from the database.
B. It creates a new document in the database.
C. It deletes a document from the database.
D. It updates the fields of a document.

Solution

  1. Step 1: Understand the purpose of getDoc()

    The getDoc() function is used to retrieve data from a specific document in Firebase Firestore.
  2. Step 2: Differentiate from other functions

    Functions like setDoc() create or update documents, while deleteDoc() removes them. getDoc() only reads data.
  3. Final Answer:

    It fetches the data of a specific document from the database. -> Option A
  4. Quick Check:

    getDoc() reads document data [OK]
Hint: Remember: getDoc() reads, setDoc() writes [OK]
Common Mistakes:
  • Confusing getDoc() with setDoc() or deleteDoc()
  • Thinking getDoc() creates documents
  • Assuming getDoc() updates data
2. Which of the following is the correct way to get a single document from a Firestore collection named users with ID user123 in JavaScript?
easy
A. const docRef = getDoc(db, 'users', 'user123');
B. const docSnap = await getDoc('users/user123');
C. const docRef = doc(db, 'users', 'user123'); const docSnap = await getDoc(docRef);
D. const docSnap = doc(db, 'users', 'user123');

Solution

  1. Step 1: Use doc() to reference the document

    The doc() function takes the database, collection name, and document ID to create a reference.
  2. Step 2: Use getDoc() with the document reference

    Pass the document reference to getDoc() to fetch the document snapshot asynchronously.
  3. Final Answer:

    const docRef = doc(db, 'users', 'user123'); const docSnap = await getDoc(docRef); -> Option C
  4. Quick Check:

    doc() creates ref, getDoc() fetches [OK]
Hint: Always create doc ref first, then getDoc(ref) [OK]
Common Mistakes:
  • Passing string path directly to getDoc()
  • Using getDoc() to create doc reference
  • Calling doc() without database argument
3. Given the following code snippet, what will be logged if the document with ID doc1 exists and has a field name with value Alice?
const docRef = doc(db, 'users', 'doc1');
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
  console.log(docSnap.data().name);
} else {
  console.log('No such document!');
}
medium
A. No such document!
B. Alice
C. undefined
D. Error: docSnap.data() is not a function

Solution

  1. Step 1: Check if document exists

    The code uses docSnap.exists() to verify the document presence, which is true here.
  2. Step 2: Access the name field from document data

    Since the document exists, docSnap.data() returns the data object, and name is Alice.
  3. Final Answer:

    Alice -> Option B
  4. Quick Check:

    Document exists, print name field [OK]
Hint: Check exists() before accessing data() [OK]
Common Mistakes:
  • Not checking exists() before data()
  • Expecting data() to return undefined if no doc
  • Confusing data() with get()
4. What is wrong with the following code snippet for getting a document from Firestore?
const docSnap = await getDoc('users/user123');
if (docSnap.exists()) {
  console.log(docSnap.data());
}
medium
A. You cannot use console.log with docSnap.data().
B. Missing await keyword before getDoc().
C. docSnap.exists() is not a valid method.
D. getDoc() requires a document reference, not a string path.

Solution

  1. Step 1: Understand getDoc() argument requirements

    The getDoc() function expects a document reference created by doc(), not a string path.
  2. Step 2: Identify the error in argument type

    Passing a string like 'users/user123' directly causes an error because it's not a valid document reference.
  3. Final Answer:

    getDoc() requires a document reference, not a string path. -> Option D
  4. Quick Check:

    getDoc() needs doc() ref [OK]
Hint: Always use doc() to create reference before getDoc() [OK]
Common Mistakes:
  • Passing string path directly to getDoc()
  • Forgetting to create doc reference
  • Assuming getDoc() accepts string paths
5. You want to fetch a user's profile document from Firestore and safely handle the case when the document does not exist. Which code snippet correctly implements this behavior?
hard
A. const docRef = doc(db, 'profiles', userId); const docSnap = await getDoc(docRef); if (docSnap.exists()) { return docSnap.data(); } else { return null; }
B. const docSnap = await getDoc(doc(db, 'profiles', userId)); return docSnap.data();
C. const docRef = doc(db, 'profiles', userId); const docSnap = getDoc(docRef); if (docSnap.exists()) { return docSnap.data(); } else { return {}; }
D. const docSnap = await getDoc('profiles/' + userId); if (docSnap.exists()) { return docSnap.data(); } else { throw new Error('Document missing'); }

Solution

  1. Step 1: Create a document reference correctly

    Use doc(db, 'profiles', userId) to get the document reference.
  2. Step 2: Await the asynchronous getDoc() call and check existence

    Use await getDoc(docRef) and check docSnap.exists() before accessing data.
  3. Step 3: Return data if exists, else return null

    This safely handles missing documents by returning null instead of causing errors.
  4. Final Answer:

    Code snippet that awaits getDoc, checks exists(), returns data or null. -> Option A
  5. Quick Check:

    Check exists() before data() to avoid errors [OK]
Hint: Always check exists() before using data() [OK]
Common Mistakes:
  • Not awaiting getDoc() causing unresolved promises
  • Accessing data without checking exists()
  • Passing string path directly to getDoc()
  • Throwing error instead of handling missing doc gracefully
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