Cloud Firestore Quicktip — DocumentSnapshot vs. QuerySnapshot

Gerwin Sturm
2 min readOct 11, 2017

Since the Firebase team launched Cloud Firestore last week, one question/problem that keeps popping up on Stackoverflow is the result of there being two different ways to retrieve data that have to be handled slightly differently. So after answering several of those questions I though it would be a good idea to put together this short article.

The samples I’m using are in JavaScript, but the behavior is essentially the same for all the other SDKs as well, and I have relevant links at the end.

Getting a single document

Retrieving a single document from Cloud Firestore is done with the following steps.

  1. Create a DocumentReference that points to the document you want.
// This points to the document with the ID 'SF'
// in the collection 'cities'
var documentReference = db.collection('cities').doc('SF');

2. Call get() on the DocumentReference to get a DocumentSnapshot.

documentReference.get().then(function(documentSnapshot) {
// check and do something with the data here.
});

3. Check if the document you specified actually exists.

if (documentSnapshot.exists) {
// do something with the data
} else {
console.log('document not found');
}

4. Retrieve and use the data.

var data = documentSnapshot.data();

Querying a collection

When querying a collection you can get zero, one or more documents as a result, by going through the following steps.

  1. Create a CollectionReference that points to the collection you want documents from.
// This points to the collection called 'cities'
var collectionReference = db.collection('cities');

2. (Optional) Create a Query based on the collection.

var query = collectionReference.where('capital', '==', true);

3. Call get() to get a QuerySnapshot.

query.get().then(function(querySnapshot) {
// check and do something with the data here.
});

4. Check whether there are any documents in the result.

if (querySnapshot.empty) {
console.log('no documents found');
} else {
// do something with the data
}

or

if (querySnapshot.size > 0) {
// do something with the data
} else {
console.log('no documents found');
}

5. Retrieve and use the data. Two different ways to do so:

// go through all the results
querySnapshot.forEach(function (documentSnapshot) {
var data = documentSnapshot.data();
// do something with the data of each document.
});

or

// get the data of all the documents into an array
var data = querySnapshot.docs.map(function (documentSnapshot) {
return documentSnapshot.data();
});

References

Basic query documentation

Detailed references for the different SDKS: Android / GO / Java / JavaScript / Node.js / Objective-C / Python / Swift

--

--

Gerwin Sturm

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