Firebase Version 9 Tutorial (Modular)

Firebase Version 8 Tutorial (Namespaced)

Firebase 9 Firestore Get A Document By ID Using getDoc()

Last modified on November 7th, 2022
Firebase Javascript

Learn how to get document by ID using the getDoc() method in Firebase version 9 Cloud Firestore Database.

The sample Firestore Database has a cities collection that has four documents in it like in the screenshot below.

Let’s get the first document of the cities collection by id.

In this case: Edmonton document using its ID (2l3bcSGs2vZBIc3RODwp)

Import Firestore Database and de-structure the three methods that we need:

  • getFirestore()Firestore Database
  • doc() → It takes references of database, collection name and ID of a document as arguments
  • getDoc() → getDoc() query gets data of a specific document from collection based on references mentioned in the doc() method.
import { getFirestore, doc, getDoc } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";

The import statement uses the CDN version of the Firebase SDK in this example.

Initialize Firestore Database

const db = getFirestore();

The getDoc() method takes a single argument which is the doc() method.

The three arguments of the doc() method are:

  • Database → db
  • Collection name → cities in this case (see the screenshot above)
  • ID of a document → 2l3bcSGs2vZBIc3RODwp in this case (see the screenshot above)

Call the doc() method, pass three arguments and assign it to a constant called docRef (short form for document reference).

const docRef = doc(db, "cities", "2l3bcSGs2vZBIc3RODwp");

Invoke the getDoc() method passing docRef as an argument to it.

The getDoc() method will return a promise, add await keyword in front of it.

Assign it to a constant called docSnap (short form for document snapshot).

const docSnap = await getDoc(docRef);

To get actual document data, call the data() method on the docSnap object.

docSnap.data();

Wrap async query with try catch block to handle client-side error if any.

try {
    const docSnap = await getDoc(docRef);
    console.log(docSnap.data());
} catch(error) {
    console.log(error)
}

Check to see if the targeted document actually exists before using it.

try {
    const docSnap = await getDoc(docRef);
    if(docSnap.exists()) {
        console.log(docSnap.data());
    } else {
        console.log("Document does not exist")
    }

} catch(error) {
    console.log(error)
}