Home > Back-end >  firestore data structure
firestore data structure

Time:01-06

im building an app with android studio-java, firestore and firebase auth. I need help on how to save the data.

The app has 3 games, the goal is to save users. score date (DD/MM/YY for each score), and high score for each game. i need to save last 5 scores for each game. My first attempt is to do it with 1 collection called "users".

user class:

private String name;
private String email;
private HashMap<Integer, Date> game1_Scores;
private HashMap<Integer, Date> game2_Scores;
private HashMap<Integer, Date> game3_Scores;
private int game1_HighScore;
private int game2_HighScore;
private int game3_HighScore;

my question:

  1. what is the best way to override the oldest score with new score ?
  2. i wanna be able to show in app a list of HighScores, high to low from all users. how do I do it ?
  3. should i do a "scores" collection. how do i connect score to user?

Any help will be appreciated.

EDIT: my db screenshot enter image description here

p.s. How to control the order of the fields when adding a new User document.

CodePudding user response:

I recommend that you model it as follows:

private String name;
private String email;
// If the number of games grows too much, new modeling will be necessary.
private List<GameScore> game1Scores;
private List<GameScore> game2Scores;
private List<GameScore> game3Scores;
private int game1HighScore;
private int game2HighScore;
private int game3HighScore;

GameScore will be a class with the field GameName or GameId, score and maybe createdAt to set the time of the game.

Afterwards, I recommend that you save all matches in a collection. Maybe this way:

Collection: matchs
In this collection you will save the GameScore and player id for each match.

Whenever a document is inserted into the match collection, you will trigger a cloud function to update the player rank and global rank.

The global rank you can update every few minutes to avoid a lot of writing in the same document.

Remember to query correctly to avoid a large number of reads.

CodePudding user response:

  1. what is the best way to override the oldest score with new score ?

In current data struture in your screenshot, You can just caompare exits score in client see if need to update scores.

  1. i wanna be able to show in app a list of HighScores, high to low from all users. how do I do it ?
  2. should i do a "scores" collection. how do i connect score to user?

You can put score and user id in a same document, Then put all documents in same collection 'scores' like you said. If specific user need to get self top three scores just run query on these two fields. You can also using collection group to achive this it depend on your case.

  • Related