DEV Community

Cover image for Firebase 9 Firestore Get A Document By ID Using getDoc()
Raja Tamil
Raja Tamil

Posted on • Originally published at softauthor.com

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

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.

alt text

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 references mentioned in the doc() method.
import { getFirestore, doc, getDoc } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";
Enter fullscreen mode Exit fullscreen mode

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

Initialize Firestore Database:

const db = getFirestore();
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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

docSnap.data();
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)