Firebase: How to get the $id of an object after I authenticate using angularFire

Firebase has the $onAuth method that listens for changes to the client's authentication state. If the client is authenticated, the callback will be passed an object that contains the uid. Here is my question: Based on this uid, how can I get the the $id for this object.

This is how my data looks like in firebase:

profile {
   -K2a7k9GXodDriEZrM3f {
      email: "[email protected]"
      gravatar: "https://www.gravatar.com/avatar/1d52da55055f0c8..."
      uid: "3f9e0d53-4e61-472c-8222-7fc9f663969e"
     name: "ale"
    }
}

I am using

auth.$onAuth(function (authData) {
    if (authData) {
      authData.profile = //here I want the $id of the object 
    }
})

All I see I can do with the authData response is to get the uid of the object by using:

$firebaseObject(ref.child('profile').child(authData.uid));

This authData does not contain the $id (i.e. the -K2a7k9GXodDriEZrM3f) of the object. And that is what I am looking for in order to have the user's information available. Is there a way to achieve this?

Thanks.

Upvotes: 0

Views: 767

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599601

If an object has a natural unique ID, you should usually store the object under that ID. Using push IDs in those cases adds no value and only complicates things.

Most developers using Firebase do as the "Storing User Data" section in the documentation illustrates: they store users by their uid. If you follow that guideline, you can find the key as authData.uid.

If you decide to stick to your current course, you can find the key for the user with:

ref.child('profile').orderByChild('uid').equalTo(authData.uid).once('child_added', function(snapshot) {
    console.log(snapshot.key());
});

But you will be making it harder for the database to find your user, thus limiting the scalability of your app.

Upvotes: 3

Related Questions