armand
armand

Reputation: 703

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

I have some location data with the following structure.

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

I am trying to reformat the geo-code info for all businesses that have it by reading the separate lat and long info and using push() to write a latLng object containing both keys.

I am able to create the object and log it to the console but when I try to call the object on the business object, its undefined. I attempted this via set() and push() in the firebase docs.

I tried the version below as well as fb.child('latLng').push({lat: snapshot.val().latitude, lng: snapshot.val().longitude});. Can not get it to go.

<!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>

Upvotes: 2

Views: 127

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598887

There's two mistakes that I can see:

  1. You're setting your latLng as a child of your root fb reference
  2. You're using push() for a structure that seems to be a named child

Solution for these two:

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

Upvotes: 1

Related Questions