Firebase retrieve data under certain child

2019-07-13 12:25发布

问题:

I was having some trouble when trying to retrieve from firebase. Here is my firebase structure:

What I tried to do is firstly, I wanted to get list of receiptItemID in the first picture. Then, after I get the IDs, for each ID, I wanted to get its quantity and type. After that, I will store them into array and perform 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 the itemKey. However, when I tried to get the details of each receiptItem by the console.log that part, it prints out undefined for both. Any ideas on how to retrieve the data?

回答1:

You don't need the forEach cycle, it's one level too deep. Instead, use the 'data' argument directly. 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 the forEach of your sample code, itemDetail will be equal to "Farmland" instead of the whole object; thus, subtype and quantity are null. In the new callback, itemDetail will be equal to the whole object, so subtype and quantity can be successfully declared.



回答2:

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 second retrieval you already have access to receiptItems/itemKey .This is a particular entry in receiptItems , not the whole receiptItems array.
                                                                         So no need to apply data.forEach() once more as there is only one record. We apply data.forEach() to fetch an array of records/object. In your case it is just one entry.