Search⌘ K
AI Features

Read data from Cloud Firestore

Explore various methods to read data from Cloud Firestore in this lesson. Learn to fetch single documents with getDoc, retrieve collections with getDocs, and listen to real-time updates using onSnapshot. By understanding these techniques, you will be able to manage dynamic data effectively in your Firebase web applications.

There are multiple ways to read data from the Cloud Firestore database. The method used depends on the behavior desired for our application. Let’s dive into these methods!

Use the getDoc function

The getDoc function retrieves the contents of a single document in the database. As its argument, this function takes a reference to the document to be fetched. It returns a JavaScript promise that resolves with a snapshot of the document’s current content.

Within the document’s snapshot, we have access to some Javascript methods we can use to check each document’s existence and obtain the data inside it:

Javascript (babel-node)
import { doc, getFirestore, getDoc } from "firebase/firestore";
import { firebaseApp } from "../services/firebase";
const firestore = getFirestore(firebaseApp);
const docRef = doc(firestore, "users/test@educative.io");
export const retrieveDoc = async () => {
const docSnapshot = await getDoc(docRef);
if (docSnapshot.exists()) {
const docData = docSnapshot.data();
console.log(docData);
}
};

In line 11, we use the exists method to check if ...