0
0
FirebaseHow-ToBeginner · 3 min read

How to Read Document from Firestore: Simple Guide

To read a document from Firestore, use the getDoc() function with a reference to the document created by doc(). This fetches the document snapshot, from which you can access data using data().
📐

Syntax

To read a document, first create a reference to it using doc(). Then call getDoc() with that reference. The result is a document snapshot. Use data() on the snapshot to get the document's fields.

  • doc(db, collectionName, documentId): points to the document.
  • getDoc(docRef): fetches the document snapshot.
  • snapshot.exists(): checks if the document exists.
  • snapshot.data(): gets the document data as an object.
javascript
import { getFirestore, doc, getDoc } from "firebase/firestore";

const db = getFirestore();
const docRef = doc(db, "collectionName", "documentId");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  const data = docSnap.data();
  // use data
} else {
  // document does not exist
}
💻

Example

This example shows how to read a user document from the users collection with ID user123. It prints the user's name if the document exists or a message if it does not.

javascript
import { initializeApp } from "firebase/app";
import { getFirestore, doc, getDoc } from "firebase/firestore";

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function readUser() {
  const docRef = doc(db, "users", "user123");
  const docSnap = await getDoc(docRef);

  if (docSnap.exists()) {
    console.log("User name:", docSnap.data().name);
  } else {
    console.log("No such user!");
  }
}

readUser();
Output
User name: Alice
⚠️

Common Pitfalls

  • Forgetting to await getDoc() causes unresolved promises.
  • Not checking exists() can lead to errors when accessing data of a missing document.
  • Using wrong collection or document IDs results in no data found.
  • Not initializing Firestore properly before reading.
javascript
/* Wrong way: missing await and no exists check */
const docSnap = getDoc(docRef);
console.log(docSnap.data()); // Error: data() on Promise

/* Right way: await and check exists */
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
  console.log(docSnap.data());
} else {
  console.log("Document not found");
}
📊

Quick Reference

Remember these steps to read a Firestore document:

  • Create a document reference with doc(db, collection, id).
  • Use await getDoc(docRef) to fetch the snapshot.
  • Check snapshot.exists() before accessing data.
  • Access fields with snapshot.data().

Key Takeaways

Always await the getDoc() call to get the document snapshot.
Check if the document exists with exists() before reading data.
Use doc() to create a reference to the exact document you want.
Initialize Firestore properly before trying to read documents.
Handle the case when the document does not exist to avoid errors.