Lloyd Banks Lloyd Banks - 1 year ago 30
Javascript Question

Setting Your Own Key When Adding an Object to Firebase - AngularFire

I can use the following to add an object to my Firebase data store:

var uniqueId = {
name: "a name",
location: "new york"
// do something on success
}, function(){
// do something if call fails

The above will add an object into my data store and if the add is successful, an ID generated by Firebase is returned. The object I just added is saved under this key.

Is there a way for me to specify what the key name is when I add to my data store?


Everything in Firebase is a URL.

Take the following URL for example.


Let's say we want to create a user with a key of 1 as a child at this location. Our URL would look like this.


To create a user using AngularFire we can create a reference at the users node and call $child(1) to create a reference to that location.

var usersRef = new Firebase('https://myapp.firebaseio.com/users');
var userRef = new Firebase('https://myapp.firebaseio.com/user/1');

$scope.users = $firebase(usersRef);

// these are the same
$scope.userOne = $firebase(userRef);
$scope.userOne = $scope.users.$child(1);

Then we can use $set to store the value of the user at that location.

var usersRef = new Firebase('https://myapp.firebaseio.com/users');
$scope.users = $firebase(usersRef);
  first: 'Vincent',
  last: 'Van Gough',
  ears: 1

In your case it would be:

var uniqueId = {
    id: 1,
    name: "a name",
    location: "new york"

Remember that using $set will destroy any previous data at that location. To non-destructively update the values use $update.