Structuring a friend list in a Firebase database

2019-08-19 00:48发布

问题:

I am looking for the best way (or at least the right way) to implement a friend system Firebase database in which each user in the database has his own information (his name, profile picture, email, etc.) and a friend list.

The problem is that I can't think of a good, efficient way to store the information inside the database, for example, if I store the data in the following way -

{
    "users": {
        "johnappleseed": {
            // name, profile picture URL, email, phone, etc...
            "friends": {
                "alice": true,
                "bob": true,
                "james": true,
                "johnappleseed2": true,
                // ...
            }
        },
        "johnappleseed2": {
            // ...
        }   
    }
}

and I want the app to show the list of friends of a certain user (which shows the friends' names, profile pictures, etc.) I would still need to perform a server request for each one of the friends in the list (while, AFAIK performing lots of server requests is considered a bad practice) to grab whatever information I want to display beyond their username... Also, what happens when a user changes their username?

Can anyone suggest a better solution or a structure that would make more sense?

回答1:

There is a good read about structuring data on firebase on https://firebase.google.com/docs/database/web/structure-data

In your case I would do it something like this

  /users:
        21532761536: <-- user id
            name: henk
            birthdate: 14-05-2016
        27361726362:
            name: priscilla
            birthdate: 14-05-2016

    /friends:
        21532761536: <-- user id (henk)
            27361726362: true, <-- friends user id (priscilla)
            18237821732: true,
        27361726362:
            72163721637: true,