Query firestore database for document id

I am a bit late, but there is actually a way to do this

db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()

This might be useful when you're dealing with firebase security rules and only want to query for the records you're allowed to access.


Try this:

db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get()

(The first query is looking for an explicit user-set field called 'id', which probably isn't what you want.)


You can use the __name__ key word to use your document ID in a query.

Instead of this db.collection('books').doc('fK3ddutEpD2qQqRMXNW5').get() you can write

db.collection('books').where('__name__', '==' ,'fK3ddutEpD2qQqRMXNW5').get().

In this case you should get an array of length 1 back.

The firebase docs mention this feature in the rules documentation. https://firebase.google.com/docs/reference/rules/rules.firestore.Resource


June, 2021

The new v9 modular sdk is tree-shakeable and results in smaller compiled apps. It is recommended for all new Firestore apps.

import { doc, getDoc } from "firebase/firestore";

const snap = await getDoc(doc(db, 'books', 'fK3ddutEpD2qQqRMXNW5'))

if (snap.exists()) {
  console.log(snap.data())
}
else {
  console.log("No such document")
}

This is based on the example from the firestore docs

import { doc, getDoc } from "firebase/firestore";

const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
  console.log("Document data:", docSnap.data());
}
else {
  // doc.data() will be undefined in this case
  console.log("No such document!");
}

You could make this into a helper function

async function getDocument (coll, id) {
  const snap = await getDoc(doc(db, coll, id))
  if (snap.exists())
    return snap.data()
  else
    return Promise.reject(Error(`No such document: ${coll}.${id}`))
}

getDocument("books", "fK3ddutEpD2qQqRMXNW5")