Firebase检索某个孩子的数据 [英] Firebase retrieve data under certain child
问题描述
我试图做的是首先,我想在第一张图片中得到receiptItemID列表。然后,我得到的ID后,每个ID,我想要得到它的数量和类型。在这之后,我将它们存储到数组中,并执行一些排序。
这是我的代码:
<$ p $ ($'$'); var query = firebase.database()。ref('');
query.once('value',data => {
data.forEach(subtypeSnapshot => {
var itemKey = subtypeSnapshot.key;
var query = firebase.database()。ref('')。child(itemKey);
});
});
});
我设法得到itemKey。但是,当我试图通过 console.log
那部分来获取每个receiptItem的细节时,它打印出两个undefined。关于如何检索数据的任何想法?
您不需要forEach循环,这是一个太深的级别。相反,直接使用数据参数。这个新的回调应该可以工作:
pre $ var itemDetail = data.val();
var subtype = itemDetail.type;
var quantity = itemDetail.quantity;
console.log(subtype +''+ quantity);
在forEach示例代码的第一个迭代中,itemDetail将等于Farmland整个对象的;因此,子类型和数量是空的。在新的回调中,itemDetail将等于整个对象,因此可以成功声明子类型和数量。
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?
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.
这篇关于Firebase检索某个孩子的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!