尝试使用Firebase并尝试获取动态添加的新添加的子项。我怎样才能检索:pi0usqkj16o?
var availability = database.ref("games/setup");
availability.once("value", function(snapshot){
console.log(JSON.stringify( snapshot.val() ) );
});
snapshot.val()
给了我以下内容:
{
"pi0usqkj16o":{
"player1":"ed",
"player1Choice":"",
"player1Wins":0,
"player2":"",
"player2Choice":"",
"player2Wins":0,
"total":0
},
"wpgnfq1swac":{
"player1":"ed",
"player1Choice":"",
"player1Wins":0,
"player2":"",
"player2Choice":"",
"player2Wins":0,
"total":0
}
}
最终目标是定位动态创建的新创建的目录(子)并给出序列号名称。也许做这样的事情? var name = pi0usqkj16o; database.ref(" somefolder /" + name); `
但是如何才能将上述json中的序列单独隔离?
//App Code
//INITIALIZE FIREBASE
firebase.initializeApp(config);
var database = firebase.database();
var Methods = {
//Makes a new serial (ex. pi0usqkj16o)
function uniqueId(){
return Math.random().toString(36).substr(2, 16);
}
//checks if a game room is already available
initialCheck: function(callback){
var availability = database.ref("games/setup");
availability.once("value", function(snapshot){
//if there is no readily available room already created..create a new room
if(snapshot.numChildren() < 1){
var gameName = uniqueId();
availability.update({
[gameName]: {player1: "ed", player2: "", player1Choice: "", player2Choice: "", player1Wins: 0, player2Wins: 0, total: 0}
});
}
else{
var room = snapshot.key;
// Need to find the room name to be able to assign it to the user.
console.log("room is: " + room );
}
});
}
答案 0 :(得分:0)
为了获得那个EXACT键,必须有一些你可以轻松参考的独特数据。这是一个想法:
{
"pi0usqkj16o":{
"player1":"ed",
"player1Choice":"",
"player1Wins":0,
"player2":"",
"player2Choice":"",
"player2Wins":0,
"total":0,
"gameNumber":1
},
"wpgnfq1swac":{
"player1":"ed",
"player1Choice":"",
"player1Wins":0,
"player2":"",
"player2Choice":"",
"player2Wins":0,
"total":0,
"gameNumber":2
}
}
我添加了一个游戏号码&#39;对于你的数据,每场比赛后应该是unqiue。现在要获得确切的密钥:
firebase.database().ref('games/setup').once("value", function(snapshot){
var data = snapshot.val();
if (data && snapshot.child('gameNumber').val() === '1'){
console.log(snapshot.key);
} else {
console.log("no data");
}
});
这应该返回您要查找的密钥。当然,你需要坐下来思考一种重新构建数据的方法,以便进行这样的查询。
也给这个读一读: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot