I want to add entries to Realtime database a particular firebase collection

57 Views Asked by At

(I am adding geofire locations for businesses. I am using this to do that currently:

var firebaseRef = push(ref(getDatabase()));
var geoFireInstance = new geofire.GeoFire(firebaseRef); 

geoFireInstance.set(  newUserName.value, [ lat2, lon2 ] ).then(function() {
        console.log("Provided key has been added to GeoFire: ");
}, function(error) {
     console.log("Error: " + error);
});  

This is working by putting entries into random database (the first 2 entries) in the Realtime Database as shown below. I want to add new entries into BusLocations (like the last 2 entries) instead of random:

{
  "-NiaHRxzh28S4UIMXa3E": { // RANDOM
    "STEAKSHAKE": {
      ".priority": "9yzekk35e8",
      "g": "9yzekk35e8",
      "l": [
        38.5639904,
        -90.5148296
      ]
    }
  },
  "-NiaN_K_KgBL95hq-0oz": { // RANDOM
    "B": {
      ".priority": "9yzemjne3j",
      "g": "9yzemjne3j",
      "l": [
        38.5680936,
        -90.4744243
      ]
    }
  },
  "BusLocations": { // **I WANT TO ADD INTO HERE INSTEAD OF RANDOM**
    "HARDEES67890": {
      "g": "9yzej7tx7n",
      "l": [
        38.5166,
        -90.46473
      ]
    },
    "LAZYRIVERBALLWIN": {
      "g": "9yzekjhp9b",
      "l": [
       "38.5687933",
        "-90.5217678"
      ]
  },
  // ...
}
1

There are 1 best solutions below

1
On BEST ANSWER

This line gets a reference to the root of the database, and then generates a new reference at that location.

var firebaseRef = push(ref(getDatabase()));

As you then feed this into your Geofire constructor, each time you load the page, it will point at a new generated reference. To fix this and always target the same location, you need to remove push() and specify the key instead.

var firebaseRef = ref(getDatabase(), "BusLocations"); // read as "using the given database, get a reference to BusLocations"

The rest of your code should remain the same.