如何使用.push或set在Firebase中创建新的子键?

时间:2016-02-02 02:39:49

标签: javascript api firebase

我有一些具有以下结构的位置数据。

[business:
     Joes Pizza:{
accountid:1818
address:32, Angle des Rue des Nimes et Blvd. Toussaint Louverture,
city:Anytown
country:USA
created:At10/26/2015 7:27:42 PM
heading: Fast Food
headingid: 178
latitude: 18.572203
longitude:-72.306747
name: Joes Pizza 
objectId:x9VRotBU2O
phonenumber:1 509 473 6003
website:http://pizza.com
    },
]

我正在尝试通过读取单独的lat和long信息并使用push()编写包含两个键的latLng对象来重新格式化所有拥有它的商家的地理代码信息。

我能够创建对象并将其记录到控制台,但是当我尝试在业务对象上调用该对象时,它是未定义的。我通过firebase文档中的set()push()尝试了此操作。

我尝试了以下版本以及fb.child('latLng').push({lat: snapshot.val().latitude, lng: snapshot.val().longitude});。不能让它去。

<!doctype html>
<html>
<head>
<script src="https://cdn.firebase.com/js/client/2.4.0/firebase.js"></script>

</head>
<body>
<p>Geoloc</p>
<script>
var fb = new Firebase("https://crackling-fire.firebaseio.com/business");

// Retrieve relevant data
fb.on("child_added", function(snapshot) {
  var place = snapshot.val();
  var latLng = {lat: snapshot.val().latitude, lng: snapshot.val().longitude}
  if (place.hasOwnProperty('longitude') && place.hasOwnProperty('latitude'))
    {

    fb.child('latLng').push(place.latLng);

    console.log(place.name, place.latLng);
    console.log(latLng);
    };
  }, function (errorObject) {
    console.log("The read failed: " + errorObject.code);
});
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

我可以看到两个错误:

  1. 您正在设置latLng作为您的根fb参考的孩子
  2. 您正在使用push()获取一个似乎是名为child 的结构
  3. 解决这两个问题:

    fb.on("child_added", function(snapshot) {
      var place = snapshot.val();
      if (place.hasOwnProperty('longitude') && place.hasOwnProperty('latitude')) {
        snapshot.ref().child('latLng').set({lat: place.latitude, lng: place.longitude});
      };
    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
    });