Firebase Firestore Guides show how to iterate documents in a collection snapshot with forEach
:
db.collection("cities").get().then(function(querySnapshot) { querySnapshot.forEach(function(doc) { console.log(doc.id, " => ", doc.data()); }); });
I imagined it would support map
as well, but it doesn't. How can I map the snapshot?
There are three ways to retrieve data stored in Cloud Firestore. Any of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data once. Set a listener to receive data-change events.
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
snapshotChanges() Metadata provides you the underyling DocumentReference , document id, and array index of the single document. Having the document's id around makes it easier to use data manipulation methods.
The answer is:
querySnapshot.docs.map(function(doc) { # do something })
The Reference page for Firestore reveals the docs
property on the snapshot.
docs non-null Array of non-null firebase.firestore.DocumentSnapshot
An array of all the documents in the QuerySnapshot.
Got pretty sick and tired of Firestore returning stuff in their classes or whatever. Here's a helper that if you give it a db
and collection
it will return all the records in that collection as a promise that resolves an actual array.
const docsArr = (db, collection) => { return db .collection(collection) .get() .then(snapshot => snapshot.docs.map(x => x.data())) } ;(async () => { const arr = await docsArr(myDb, myCollection) console.log(arr) })()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With