Firebase Cloud Firestore query not finding my document

Tags: , ,



Here’s a picture of my data: enter image description here

I’m trying to get that document. This works:

var docRef = db.collection('users').doc('jPDKwHyrFNXNTFI5qgOY');
docRef.get().then(function(doc) {
  if (doc.exists) {
    console.log("Document data:", doc.data());
  } else {
    console.log("No such document!");
  }
}).catch(function(error) {
  console.log("Error getting document:", error);
});

It returns:

enter image description here

I.e., if I know the document’s key I can get the document.

This doesn’t work:

db.collection('users').where('uid', '==', 'bcmrZDO0X5N6kB38MqhUJZ11OzA3')
.get().then(function(querySnapshot) {
  if (querySnapshot.exists) {
    console.log(querySnapshot.data);
  } else {
    console.log("No such document!");
  }
})
.catch(function(error) {
  console.log("Error getting document: ", error);
});

It just returns No such document! What’s wrong with my query?

Answer

The difference in your two requests is that in the first case you are retrieving one document which gives you a DocumentSnapshot which has the exists property and the data() method.

In the second case you do a query, which gives you a QuerySnapshot that has to be handled differently from a DocumentSnapshot. Instead of a single document you get a list/collection of documents. You can check if data has been retrieved using the empty or size properties, and then go through the results using the forEach method or going through the docs array:

db.collection('users').where('uid', '==', 'bcmrZDO0X5N6kB38MqhUJZ11OzA3')
.get().then(function(querySnapshot) {
  if (querySnapshot.size > 0) {
    // Contents of first document
    console.log(querySnapshot.docs[0].data());
  } else {
    console.log("No such document!");
  }
})
.catch(function(error) {
  console.log("Error getting document: ", error);
});


Source: stackoverflow