How to set a custom ID when pushing a new object into Firebase

All we need is an easy explanation of the problem, so here it is.

I am using Firebase with AngularJS in my application. When a user logs into the app with the Facebook authentication I want to create a new user object (with some properties coming from Facebook and some relative to my app) and store it in Firebase. It’s simple, I’m pushing the new User object:

...
var travelBidsFirebaseRef = new Firebase(url);
var newUserRef = travelBidsFirebaseRef.child("user").push(user, callback);
...

push() generates a unique ID, smth. like: -J08SgyOeOU_fFb1CB3G. So the only way I can access this User object is by using this ID:

angularFire(travelBidsFirebaseRef + "/user/-J08SgyOeOU_fFb1CB3G", $scope, 'user', {});

But when I receive authentication data from Facebook I have only Facebook ID and there is no way of me knowing the Firebase ID generated earlier (otherwise I would have to maintain a map of all users, which I don’t want to).
So here is the question: how do I save new User to the Firebase with a custom ID, e.g. Facebook ID?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Instead of using push(), use set() with the Facebook ID:

travelBidsFirebaseRef.child("user").child(facebookId).set(user, callback);

If you are using simple login and multiple auth providers (e.g. Facebook and Twitter at the same time) then be sure you split out your users by provider, as IDs can possibly clash

travelBidsFirebaseRef.child(“user/facebook/”+facebookId).set(user, callback);

Update

As of FirebaseSimpleLogin 1.0, you can now use uid, which is unique across providers:

new FirebaseSimpleLogin(ref, function(err, user) {
   if( err ) throw err;
   travelBidsFirebaseRef.child('user/'+user.uid).set(user, callback);
});

Method 2

You can also try something like this:

var empsRef = ref.child("employees");

empsRef.child('11111').set({
  lastname: "Lee",
  firstname: "Kang"
});

empsRef.child('22222').set({
  lastname: "Nut",
  firstname: "Dough"
});

The output should look like this:

"employees" : {
  "11111" : {
    "lastname" : "Lee",
    "firstname": "Kang"
  },
  "22222" : {
    "lastname" : "Nut",
    "firstname": "Dough"
  }
}

Method 3

do something like this:

  employees.update({
    "1" : {
      "lastname" : "Doe",
      "firstname": "John"
    },
    "2" : {
      "lastname" : "Loca",
      "firstname": "Maria"
    }
  });

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply