Getting a single document
Retrieving a single document from Cloud Firestore is done with the following steps.
// This points to the document with the ID 'SF'
// in the collction 'cities'
let documentReference = db.collection('cities').doc('SF');
get()
on the DocumentReference to get a DocumentSnapshot.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');
}
let 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.
let collectionReference = db.collection('cities');
let query = collectionReference.where('capital', '==', true);
get()
to get a QuerySnapshot.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) {
let data = documentSnapshot.data();
// do something with the data of each document.
});
let data = querySnapshot.docs.map(function (documentSnapshot) {
return documentSnapshot.data();
});