Reputation: 682
I followed the doc here on how to write a query but I am not getting any data from it. The database is already populated with the example provided by the doc
Below is my code
var db = firebase.firestore();
var citiesRef = db.collection("cities");
var query = citiesRef.where("state", "==", "CA");
query.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 works fine if I didn't put any queries on it. For example (also from the doc):
var docRef = db.collection("cities").doc("SF");
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);
});
Upvotes: 2
Views: 5062
Reputation: 15569
The difference in your two requests is that in the second case you are retrieving one document which gives you a DocumentSnapshot
which has the exists
property and the data()
method.
In your not working example 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:
var db = firebase.firestore();
var citiesRef = db.collection("cities");
var query = citiesRef.where("state", "==", "CA");
query.get().then(function(results) {
if(results.empty) {
console.log("No documents found!");
} else {
// go through all results
results.forEach(function (doc) {
console.log("Document data:", doc.data());
});
// or if you only want the first result you can also do something like this:
console.log("Document data:", results.docs[0].data());
}
}).catch(function(error) {
console.log("Error getting documents:", error);
});
Upvotes: 10