Cloud Firestore Quicktip — DocumentSnapshot vs. QuerySnapshot

Gerwin Sturm
Oct 11, 2017 · 2 min read

Getting a single document

// This points to the document with the ID 'SF'
// in the collection 'cities'
var documentReference = db.collection('cities').doc('SF');
documentReference.get().then(function(documentSnapshot) {
// check and do something with the data here.
});
if (documentSnapshot.exists) {
// do something with the data
} else {
console.log('document not found');
}
var data = documentSnapshot.data();

Querying a collection

// This points to the collection called 'cities'
var collectionReference = db.collection('cities');
var query = collectionReference.where('capital', '==', true);
query.get().then(function(querySnapshot) {
// check and do something with the data here.
});
if (querySnapshot.empty) {
console.log('no documents found');
} else {
// do something with the data
}
if (querySnapshot.size > 0) {
// do something with the data
} else {
console.log('no documents found');
}
// go through all the results
querySnapshot.forEach(function (documentSnapshot) {
var data = documentSnapshot.data();
// do something with the data of each document.
});
// get the data of all the documents into an array
var data = querySnapshot.docs.map(function (documentSnapshot) {
return documentSnapshot.data();
});

References

Gerwin Sturm

Written by

Business applications and web developer, Google Developer Expert for Web Technologies until 2017, World traveller

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade