Search code examples
javascriptangularjsfirebaseangularfire

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"
}
$scope.myItems.$add(uniqueId).then(function(firebaseId){
    // 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?


Solution

  • Everything in Firebase is a URL.

    Take the following URL for example.

    https://myapp.firebaseio.com/users/
    

    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.

    https://myapp.firebaseio.com/users/1
    

    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);
    $scope.users.$child(1).set({
      first: 'Vincent',
      last: 'Van Gough',
      ears: 1
    });
    

    In your case it would be:

    var uniqueId = {
        id: 1,
        name: "a name",
        location: "new york"
    };
    $scope.myItems.$child(uniqueId.id).$set(uniqueId);
    

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