Firebase fetch data under specific child

I had problems trying to get from firebase. Here is my firebase structure:

What I was trying to do was, firstly, I wanted to get the list of receiptItemID in the first snapshot. Then, after getting the IDs, for each ID, I wanted to get its count and type. After that I will store them in an array and do some sorting.

Here is my code:

var query = firebase.database().ref('');
                  query.once( 'value', data => {
                      data.forEach(subtypeSnapshot => {
                        var itemKey = subtypeSnapshot.key;

                        var query = firebase.database().ref('').child(itemKey);

                        });
                  });
                }); 

      

I managed to get itemKey. However, when I tried to get information about each receiptItem using console.log

this part, it prints undefined for both. Any ideas on how to fetch the data?

+3


source to share


2 answers


You don't need a forEach loop, one level is too deep. Use the "data" argument directly instead. This new callback should work:

  var itemDetail = data.val();
  var subtype = itemDetail.type;
  var quantity = itemDetail.quantity;
  console.log(subtype + ' ' + quantity);

      



In the first iteration of forEach in your sample code, itemDetail will be "Farmland", not the entire object; thus, subtype and count are zero. In the new callback, itemDetail will be equal to the entire object, so the subtype and quantity can be declared successfully.

+1


source


var query = firebase.database().ref('receiptItems').child(itemKey);
                      query.once( 'value', data => {
                            var itemDetail = data.val();
                            var subtype = data.type;
                         // you may try data.toJSON().type as well
                            var quantity = data.quantity;
                         // try data.toJSON().quantity
                            console.log(subtype + ' ' + quantity);

                    });

      



In the second search, you already have access to receiptItems / itemKey. This is a specific entry in the getter, not the entire receiptItems array.
                                                                        So there is no need to apply data.forEach () again as there is only one entry. We use data.forEach () to retrieve an array of records / objects. In your case, this is just one entry.

+1


source







All Articles