Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 827
Alexander Burakevych Avatar asked Aug 05 '13 05:08

Alexander Burakevych


2 Answers

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);
});
like image 117
Kato Avatar answered Nov 08 '22 01:11

Kato


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"
  }
}
like image 21
Lee Avatar answered Nov 08 '22 02:11

Lee