Firebase未创建新的指定端点

时间:2016-06-28 19:17:02

标签: javascript jquery firebase firebase-realtime-database

下午好,我在firebase数据库中创建和写入新端点时遇到了困难。我要做的是创建一个名为savedUser的新子节点,并将新创建的端点推送到现有user节点的当前内容。这是我正在使用的代码:

// this is the initial search that sets the data in the user
// endpoint
$("#searchButton").on("click", function(){
​
    firebase.database().ref().once("child_added", function(snapshot){
    // little lesson in closure
    // dry coding
    function ez(path){
      return snapshot.child(path).val();
    }
​
    var dataObject = { 
      gamertag: ez("gamertag"),
      totalKills: ez("totalKills"),
      totalDeaths: ez("totalDeaths"),
      totalGames: ez("totalGames")
    };
    //handlebars, getting template
    var sourceTemplate = $("#list-template").html();
​
    var template =  Handlebars.compile(sourceTemplate);
    //handlebars, sending object to DOM
    var templateHTML = template(dataObject);
​
    var $templateHTML = $(templateHTML);
​
    $("#profileSearch").append($templateHTML);

​
  });

});
​
var $confirmButton = $("#confirmButton");
​
// This is supposed to fire when the "save" button is clicked
$(document).on("click", "#confirm", function(event){
  event.preventDefault()
  // referencing database again to iterate and capture value
  firebase.database().ref().once("value", function(snapshot){
    function ez(path){
      return snapshot.child(path).val();
    }
    // same procedure so far
    var savedUserData = {
      gamertag: ez("gamertag"),
      totalKills: ez("totalKills"),
      totalDeaths: ez("totalDeaths"),
      totalGames: ez("totalGames")
    }

    function saveUser(newChildPath, data){
      firebase.database().ref(newChildPath).set(data)
    }
    // call the function saves at the endpoint "savedUser" 
    saveUser("savedUser/", savedUserData);
​
​
  });
});

上面的代码没有写任何内容到我的数据库,但根据我一直在看的指南,我应该成功地做到这一点。但是这会写入我的数据库:

function saveUser(childPath, data){
      firebase.database().ref(childPath).set(data)
    }
    saveUser("savedUser/", {new: "path"});


  });
});

在我的数据库控制台上,我可以找到“/ savedUser / new”,它更新没有问题。但是当我试图从数据库中捕获数据并将其格式化为第一个示例时,它不起作用并且没有写入任何内容。实际上,savedUser端点已被删除。我必须要有一个微妙的缺失。我对Firebase并不精通。非常感谢任何帮助,如果我能提供更多信息,请告诉我。

谢谢!

1 个答案:

答案 0 :(得分:0)

我能够通过对代码进行以下更改来获得此代码:

var savedUserData = {
  gamertag: ez("user/gamertag"),
  totalKills: ez("user/totalKills"),
  totalDeaths: ez("user/totalDeaths"),
  totalGames: ez("user/totalGames")
}

上面,我引用了我想从中获取数据的路径。我需要这样做,因为我正在创建一个新的子savedUser并将其添加到根目录。这意味着当我简单地调用ez("gamertag")时,代码正在寻找名为gamertag的根中的某些内容,但实际上存储在user/gamertag中,必须通过添加{savedUser来区分1}}节点。因此,我需要在代码中更具体地在我的数据库中搜索,在目录中添加一个新文件并更完整地输入路径。