1

I have the database design below.

enter image description here

I was wondering how I would be able to use an id like KeXrsroFOeMs4XNjgC7hto retrieve the value for that document. Here is my current code:

db.collection('users',).where(id, '==', id)
    .get().then(function(querySnapshot) {
      if (querySnapshot.size > 0) {
        // Contents of first document
        resolve(querySnapshot.docs[0].data());
      } else {
        resolve("No such document!");
      }
    })
    .catch(function(error) {
      console.log("Error getting document: ", error);
    });
Juliette
  • 4,309
  • 2
  • 14
  • 31

2 Answers2

3

If you just want to fetch a single document by ID then use get() on a DocumentReference instead. You don't need a query for that:

db.collection('users').doc(id).get().then((snap) => {
  if (snap.exists) {
    const data = snap.data();
    console.log(data);
  } else {
    console.log("Document does not exist");
  }
})
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • 1
    If you really want to use a query though, you can use `FieldPath.documentId()` for the field. See https://stackoverflow.com/q/47876754, which is also a top result when I [search for the topic](https://www.google.com/search?q=querying+for+document+id+with+firestore). – Frank van Puffelen Jun 09 '22 at 19:41
0

There's a lot wrong here: db.collection('users',).where(id, '==', id). Why the "," here ('users',)? And you don't need to use .where() to achieve what you want.

Here's how to do it in a try/catch block; make sure id is defined

  try {
   const docRef = db.collection('users').doc(id);
   const doc = await docRef.get();
   if (doc.exists) {
    // Document data
    console.log(doc.data());
    } else {
    console.log("No such document!");
   }
  } catch (error) {
   console.log("Error getting document: ", error);
 }
sung
  • 321
  • 3
  • 7