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

How do you use .push or set to create a new child key in Firebase?

本文关键字:创建 密钥 Firebase push 何使用 set      更新时间:2023-09-26

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

[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
    },
]

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

我能够创建对象并将其记录到控制台,但是当我尝试在业务对象上调用该对象时,它未定义。我通过火力基地文档中的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. latLng设置为根fb引用的子项
  2. 您正在将push()用于似乎是命名子级的结构

这两个解决方案:

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);
});