[英]Firebase realtime db query showing undefined?
我的 firebase 控制台中有以下數據。
下面是上圖的 json 形式。
"Messages" : {
"fYIM9pgpGdUpXtgrC3CavJyoN" : {
"1FH4baB4LLeKhPjUqiGvj5T6DU" : {
"chat": {// all chat here
},
"chattingid" : {
"chatid" : "1FH4baB4LLeKhPjUqiGvj5T6DU"
}
},
"TCAv2NtQYdUXkF2COgZslsXARh" : {
"chat": {//all chat here
},
"chattingid" : {
"chatid" : "TCAv2NtQYdUXkF2COgZslsXARh"
}
},
}
}
我正在使用以下查詢來獲取所有 chatid 並在我的控制台中獲得兩次未定義。
firebase.database().ref("Messages/"+suid).orderByChild("chattingid").on("child_added", function(data){
console.log("You are here to see "+ JSON.stringify(data.val().chatid));
})
如何使用 firebase 查詢獲取所有聊天記錄。 可能嗎? 謝謝
數據以數組形式返回,因此您可以使用 forEach 獲取 chatid 的
firebase.database().ref("Messages/" + suid).orderByChild("chattingid").on("child_added", data => {
data.forEach(snapshot => {
console.log("You are here to see " + snapshot.val().chatid);
})
})
發表我的評論作為答案。 我有一段時間沒有使用 firebase 但我傾向於說你應該用.orderByChild("chattingid/chatid")
替換你的.orderByChild("chattingid")
) 因為 chattingid 是一個 object 並且你可能想要排序通過 chatid 中的實際文本。
因此,我建議從類似於以下內容的內容開始:
firebase.database().ref("Messages/"+suid).orderByChild("chattingid/chatid").on("child_added", function(data){
console.log("You are here to see ", data.val());
})
當您不確定為什么會看到您所看到的內容時,最好的辦法就是打印出數據並從那里縮小范圍。
如果 data 為您提供了一個數組,那么很好,您可以從那里開始工作,並在迭代步驟中使用console.log(JSON.parse(data));
或console.log(JSON.stringify(data));
得到你的目標。 如果數據未定義,那么您知道您的 firebase 查詢中有需要解決的問題
編輯
您可以考慮嘗試執行以下操作來獲取 chatid,因為通過您的查詢,您正在獲取“Messages/fYIM9pgpGdUpXtgrC3CavJyoN”,並且結果值應該類似於以下內容。
"1FH4baB4LLeKhPjUqiGvj5T6DU" : {
"chat":{// all chat here}
"chattingid" : {
"chatid" : "1FH4baB4LLeKhPjUqiGvj5T6DU"
}
},
"TCAv2NtQYdUXkF2COgZslsXARh" : {
"chat":{// all chat here}
"chattingid" : {
"chatid" : "TCAv2NtQYdUXkF2COgZslsXARh"
}
},
這些鍵與 chatids 字段匹配,因此您可能可以執行以下操作來獲取 id(或者特別是來自 json object 返回的應該與 chatids 字段匹配的鍵)。
firebase.database().ref("Messages/"+suid).orderByChild("chattingid/chatid").on("child_added", function(data){
console.log("You are here to see ",data.val());
}), function (error) {
console.log("Error: " + error.code);
});
編輯 2 -- 更新-- 為您的數據庫添加索引
我遇到了以下 SO 答案 - https://stackoverflow.com/a/27878176/3272438
您可以嘗試將以下索引規則添加到 chatid 索引
{
"rules": {
"Messages": {
"chattingid": {
".indexOn": ["chatid"]
}
}
}
}
查看以下教程,讓您在如何處理返回的數據方面找到正確的方向 - https://www.tutorialspoint.com/firebase/firebase_event_types.htm
編輯 3
因為上面的 EDIT 2 將Array [ "node_", "ref_", "index_", ]
提供給控制台,所以該代碼顯然沒有解決問題。
我利用了我在React 中遇到的一些示例,Firebase: Access values of JSON 並且還獲得了鍵值和我所做的更改以及@raphael 的答案,即循環遍歷返回的 ZA8CFDE6331BD49EB2ACZ6B81 到數組)下面的一段代碼。
嘗試以下操作:
firebase.database().ref("Messages/" + suid).orderByChild("chattingid/chatid").on("child_added", data => {
data.forEach(snapshot => {
console.log("just the val " , snapshot.val());
console.log("val.chatid " , snapshot.val().chatid);
console.log("val.chattingid.chatid " , snapshot.val().chattingid.chatid);
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.