Dportology Dportology - 2 months ago 27
Android Question

Firebase data flattening

I have a quick question about the best practices for data structure in a firebase database.

I want users of my app to be able to maintain a friends list. The firebase documentation recommends creating a schema (not sure if thats the proper word in this context) that is as flat as possible. Because of this I thought it would be a good idea to separate the friends section from the player section in the database like so:

{


"players":{
"player1id":{
"username":"john",...
},
"player2id": ...,
"player3id": ...
}


"friends": {
"player1id"{
"friends":{
"friend1Id":true,
"friend2Id":true
}
},
}
"player2id"{
"friends":{
"friend1Id":true,
"friend2Id":true
}
},
}
}


So my questions are as follows:

Is this a good design for my schema?

When pulling a friends list for one player, will the friends lists of EVERY player be pulled? and if so, can this be avoided?

Also, what would be the best way to then pull in additional information about the friends once the app has all of their IDs. e.g. getting all of their user names which will be stored as a string in their player profile.

Answer

Is this a good design for my schema?

You're already thinking in the right direction. However the "friends" node can be simplified to:

 "friends": {
   "player1id": {
     "friend1Id":true,
     "friend2Id":true
   }
 }

Remember that Firebase node names cannot use the character dot (.). So if your IDs are integer such as 1, 2, and 3 everything is OK, but if the IDs are username be careful (for example "super123" is OK but "super.duper" is not)

When pulling a friends list for one player, will the friends lists of EVERY player be pulled? and if so, can this be avoided?

No. If you pull /friends/1 it obviously won't pull /friends/2 etc.

Also, what would be the best way to then pull in additional information about the friends once the app has all of their IDs. e.g. getting all of their user names which will be stored as a string in their player profile.

Loop through the IDs and fetch the respective nodes from Firebase again. For example if user 1 has friends 2, 3, and 4, then using a for loop fetch /players/2, /players/3, and /players/4

Since firebase pull works asynchronously, you might need to use a counter or some other mechanism so that when the last data is pulled you can continue running the completion code.

Comments