Process Flow - Getting a single document
Start
Call getDoc()
Check if document exists
Return data
End
This flow shows how to get one document from Firebase Firestore: call getDoc(), check if it exists, then return data or handle missing document.
const docRef = doc(db, "users", "user123"); const docSnap = await getDoc(docRef); if (docSnap.exists()) { console.log(docSnap.data()); } else { console.log("No such document!"); }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create document reference for 'users/user123' | docRef points to 'users/user123' | docRef ready |
| 2 | Call getDoc(docRef) | Fetch document from Firestore | docSnap received |
| 3 | Check docSnap.exists() | Does document exist? | True or False |
| 4 | If True, call docSnap.data() | Retrieve document data | Data object returned |
| 5 | If False, log 'No such document!' | Handle missing document | Message logged |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| docRef | undefined | Reference to 'users/user123' | Reference unchanged | Reference unchanged | Reference unchanged |
| docSnap | undefined | undefined | Document snapshot object | Document snapshot object | Document snapshot object |
| data | undefined | undefined | undefined | undefined | Document data or undefined |
Getting a single document in Firebase Firestore: - Create a document reference with doc(db, collection, id) - Use await getDoc(docRef) to fetch - Check docSnap.exists() before accessing data - Use docSnap.data() to get document fields - Handle missing documents gracefully
getDoc() function do in Firebase when working with a single document?getDoc()getDoc() function is used to retrieve data from a specific document in Firebase Firestore.setDoc() create or update documents, while deleteDoc() removes them. getDoc() only reads data.users with ID user123 in JavaScript?doc() to reference the documentdoc() function takes the database, collection name, and document ID to create a reference.getDoc() with the document referencegetDoc() to fetch the document snapshot asynchronously.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!');
}docSnap.exists() to verify the document presence, which is true here.name field from document datadocSnap.data() returns the data object, and name is Alice.const docSnap = await getDoc('users/user123');
if (docSnap.exists()) {
console.log(docSnap.data());
}getDoc() function expects a document reference created by doc(), not a string path.doc(db, 'profiles', userId) to get the document reference.await getDoc(docRef) and check docSnap.exists() before accessing data.null instead of causing errors.Pass the test and this pattern moves unknown