Skip to content Skip to sidebar Skip to footer

Firebase Retrieve Data Under Certain Child

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 pi

Solution 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.

Solution 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 wellvar 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.

Post a Comment for "Firebase Retrieve Data Under Certain Child"