Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Way To Store Users In Firebase Database

currently I am working on a Database Layout for my Firebase Database. I am looking through many different tutorials on how the layouts should look, but I am getting a bit confused on what is proper.

I am not sure on what the users should be stored as, let me give you an example:

{
  "users": {
    "alanisawesome": {
      "nickname": "Alan The Machine"
    },
    "gracehop": {
      "nickname": "Amazing Grace"
    }
  }
}

In the example above from the Firebase Legacy docs they are storing users by their Usernames. Yet in another example I found the following:

{
  "users": {
    "123": {
      "name": "Kato"
    },
    "234": {
      "name": "Anant"
    }
  }
}

Here they are storing the users with a UID. Then you can simply just push() new users, and their IDs are random keys such as the following -JRHTHaKuITFIhnj02kE.

Which of the above is the best way to store users? Username, Custom made UID, or random generated Key?

like image 802
Michael Jones Avatar asked Dec 10 '22 15:12

Michael Jones


1 Answers

Firebase push ids are great when you have a collection that you want to order chronologically, where the individual items don't have a natural key. So a list of blog posts, chat messages, etc.

But when items have a natural key, it is usually better to store them under that natural key. Users have a unique id, usually referred to as their uid. Unless you have a reason not to do so, store the users under their uid. By storing them under their uid, you can easily look up the data for a given user: ref.child('users').child(user.uid). If you stored the users under a generated key (such as a push id), you'd have to perform a query to find the same record.

The examples you got from the documentation are using a different naming scheme. The reason for that is that both push IDs and UIDs would have led to more confusion than we wanted in the docs at that point. That's why we chose short, readable keys in those cases.

like image 147
Frank van Puffelen Avatar answered Jan 18 '23 23:01

Frank van Puffelen