Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map items of collection snapshot in Firebase Firestore

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?

like image 649
João Souza Avatar asked Oct 06 '17 21:10

João Souza


People also ask

How do I get data from firestore 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.

What is onSnapshot in Firebase?

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.

What is snapshotChanges?

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.


2 Answers

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.

like image 150
João Souza Avatar answered Oct 12 '22 06:10

João Souza


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) })() 
like image 30
corysimmons Avatar answered Oct 12 '22 06:10

corysimmons