Reading a Single Document
If you already know the document ID, you can read that document with getDoc. It's most often used for user profiles, note detail pages, and product detail pages.
Code Example
javascript
import { getFirestore, doc, getDoc } from 'firebase/firestore';
const db = getFirestore();
async function readNote(noteId) {
const noteRef = doc(db, 'notes', noteId);
const snapshot = await getDoc(noteRef);
if (!snapshot.exists()) {
console.log('Note not found');
return;
}
console.log('Note data:', snapshot.data());
}
readNote('Lk9aPq82xYzExample');What does this code do?
getDoc returns a document snapshot. Checking whether the data actually exists with snapshot.exists() before calling snapshot.data() is the safe way to do it.
Common mistake
Calling snapshot.data() straight away when the document doesn't exist often causes an undefined error in the UI. Always handle the not-found state explicitly.