1

I'm trying to iterate over the nodes of a given collection in Firestore, but it does not seems to work. I'm new on Javascript so the data structure is not well clear to me.

The following code was my attempt. I've failed because it appears an errors which tells me that the forEach() function is not defined. However, it does not make sense to me. This documentation shows that the return of the get function is Promise<QuerySnapshot>. On the sequence, this doc shows the method of the QuerySnapshot objects and it appears the forEach method.

 var myarray = firebase.firestore().collection('cards').get();  
 myarray.forEach( k => {
    console.log(k)
 });

I came here seeking for help. Could someone explains me why the forEach method does not exists for the given object and how can I iterate over the child nodes on the cards collection, so I could check their attributes?

Gilgamesh
  • 589
  • 1
  • 6
  • 20

2 Answers2

3
firebase.firestore().collection('cards').get().then(snapshot => {

    snapshot.forEach(doc => {
        console.log(doc.data());
    });

});

The then() method returns a Promise. Basically you need to wait until the data is returned from firebase before you can access and use it. Then you just need to loop over the snapshot that is returned from the promise.

Jonathan Irvin
  • 896
  • 8
  • 17
0

Try to console.log(firebase.firestore().collection('cards').get());

It appears, it might be null or something else, but clearly not an array, otherwise the .forEach() method should work,

as you can see when doing this:

    var myarray = [1,2];  
 myarray.forEach( k => {
    console.log(k)
 });

https://jsfiddle.net/21c9sf7L/

DigitalJedi
  • 1,577
  • 1
  • 10
  • 29