[英]node.js: iterate through nested firebase JSON tree
我試圖從node.js訪問嵌套的firebase樹,如下所示。
ref.forEach( function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
它總是會告訴我ref.forEach不是一個函數。
TypeError: refPrices.forEach is not a function
我已將這些定義如下。
var db = admin.database();
var ref = db.ref("users");
我檢查了這些答案
如何使用Firebase / Node.js迭代大型數據集?
但我相信根據那些我上面的代碼應該工作,所以我真的很困惑。 此外,我試圖通過循環替換forEach,但我得到了
TypeError: ref.length is not a function
所以我無法計算循環的最大值。 我也試過了
ref.once("value", function(snapshot0) {
snapshot0.child("Meals").forEach( function(snapshot1) {
console.log(snapshot1.val);
});
});
但在這種情況下它會拋出錯誤
TypeError: snapshot0.forEach is not a function
所以我幾乎還有同樣的問題。 我無法解決我的例子與上述解決方案的鏈接不同的地方?
編輯:這是我的JSON樹的樣子(根據Frank的要求)。 我只略微縮短了userID。
"users" : {
"ugkvjTuXW2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 1, 1, 1, 1, 1, 1 ]
}
}
},
"oJJ1Cojia2" : {
"Meals" : {
"Meal_2" : {
"priceHist" : [ null, 1, 4, 4, 1, 1, 1 ]
},
"Meal_3" : {
"priceHist" : [ null, 1, 1, 1, 1, 10, 1 ]
},
"Meal_4" : {
"priceHist" : [ null, 1, 5, 1, 1, 7, 1 ]
},
"Meal_5" : {
"priceHist" : [ null, 3, 1, 1, 1, 12, 1 ]
}
}
}
}
在您的第一個片段中: DatabaseReference
只不過是Firebase數據庫中某些數據的路徑。 數據本身不在ref中,因此您無法循環數據。
很難說你的第二個片段出了什么問題,因為我們不知道/users
下的數據是什么樣的。 請編輯您的問題,以包含重現問題所需的JSON最小片段(如文本,請不要截圖)。 您可以通過單擊Firebase數據庫控制台中的“導出JSON”鏈接來獲取此信息。
更新
如果檢索/users
的值,則會獲得包含所有用戶的快照。 所以第一級孩子是每個用戶的節點。 然后在那里你有每個用戶的飯菜。 您的代碼缺少第一級的循環,因此:
var ref = admin.database().ref("users");
ref.once("value", function(userSnapshot) {
userSnapshot.forEach(function(userSnapshot) {
userSnapshot.child("Meals").forEach(function(mealSnapshot) {
console.log(mealSnapshot.val());
});
});
});
另請注意,您使用的是Firebase建議的數字索引。 請參閱有關陣列的此博客文章以及有關處理集合的Firebase文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.