Im working on a project for school with FireStore.
I need to add 4 fields individually to my FireStore db. They are called "player1", "player2", "player3" and "player4". When the first person runs the code, "player1" is added. When the second person runs the code, "player2" is added, but "player1" is deleted. Same for the other 2. Which is weird, since it should not be doing that. Here’s the code that adds the field
public void initPlayer(){
getFirestore();
HashMap<String, String> playerQuote = new HashMap<>();
HashMap<String, HashMap<String, String>> players = new HashMap<>();
playerQuote.put("money", "140");
playerQuote.put("name", ControllerManager.getPlayer().getPlayerID().toString());
//The PlayerID is different for every player
playerQuote.put("color", "Green");
playerQuote.put("haan", "0");
playerQuote.put("gans", "0");
playerQuote.put("kat", "0");
playerQuote.put("hond", "0");
playerQuote.put("schaap", "0");
playerQuote.put("bok", "0");
playerQuote.put("ezel", "0");
playerQuote.put("varken", "0");
playerQuote.put("koe", "0");
playerQuote.put("paard", "0");
players.put((ControllerManager.getPlayer().getPlayerID()), playerQuote);
this.db.collection("game")
.document("Players")
.set(players);
}
The code is written in such a way that it first checks what players are in the database. So if player1 is present, but player2 isn’t, player2 will be added. But since then player1 is deleted, the next person to run the code will add player1 again and delete player2.
I really have no idea why its not working the way it should. Im not deleting anything anywhere, so why does it still delete anyway?
Here’s how the database should look like:
2
Answers
I fixed it by changing .set(players) to .update(players). .set() is rewriting the document, while .update() is updating the document. Note that .update does not allow a <string, hashmap<string, string>>, so i had to change it to <string, object>.
The
Players
in your Firestore screenshot is a Document, not a Collection.The Firestore data model always alternates Collections and Documents, so you can’t immediately nest a
Players
collection under thegame
collection. Usually I’d have a game ID as a document level in between them, but if there’s only one game – give the required document a fixed name, such asdefault
.So then the data model becomes:
If you want to stick to your current data model and store all players in a single document, you will have to make sure that players don’t overwrite each other’s data. This means, you’ll want to use a transaction to first read the
Players
document and then update it.