Read a Single Firestore Document

The best way to read a single Firestore document depends on the data you have access to. Each of the following strategies will execute a single document read, but uses different methods based on the underlying data model.

Strategies

With the ID

Reading a document by its ID, path, or reference is simple.

file_type_js_official firestore.js
async function getDoc(id) {
  const snapshot = await db.collection('users').doc(id).get();
  const data = snapshot.data();
}

With a Unique Field

A common use case is to fetch a user by their unique email address or username. In this scenario, you may have access to the field value, but not the ID. Make a query, then check it for emptiness.

async function getUserByEmail(email) {
  // Make the initial query
  const query = await db.collection('users').where('email', '==', email).get();

   if (!query.empty) {
    const snapshot = query.docs[0];
    const data = snapshot.data();
  } else {
    // not found
  }

}

With a Non-Unique Field

Another common use-case is to fetch the most recent post In this case, we order by the desired field, then limit the result set.

async function getMostRecent() {
  // Make the initial query
  const query = await db.collection('posts').orderBy('createdAt').limit(1).get();

  const snapshot = query.docs[0];
  const data = snapshot.data();

}

Learn more about Firestore Data Modeling in the full course.

Questions?

Ask questions via GitHub below OR chat on Slack #questions