The code uses docSnap.exists() to verify the document presence, which is true here.
Step 2: Access the name field from document data
Since the document exists, docSnap.data() returns the data object, and name is Alice.
Final Answer:
Alice -> Option B
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
Step 1: Understand getDoc() argument requirements
The getDoc() function expects a document reference created by doc(), not a string path.
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.
Final Answer:
getDoc() requires a document reference, not a string path. -> Option D
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?