Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+7 votes

When adding entries into my firebase database, I create multiple documents for each time I add entries. This is a problem since I only want to have 1 set of values to save and change. Is there a way to reference a single document to work with at a time in my code?

Here is a snippet of my code that I use to add elements to the database and it creates random document IDs that it grabs from randomly when I get() values:

FirebaseFirestore db = FirebaseFirestore.getInstance();

db.collection("birds")
                .add(birdCounts)
                .addOnSuccessListener(...
asked in CSC490_Spring202021 by (1 point)

1 Answer

+1 vote

Note: In the past, most student projects have used the "Realtime Database" rather than the "Cloud Firestore". There are pros & cons. Comparison here: https://firebase.google.com/docs/firestore/rtdb-vs-firestore

As you probably realized, your current code is adding a new document to the collection. This is very useful, say, whenever a user posts something new on a message board, and you want to create a new "post" object with a unique ID to represent that post.

In this case, instead, it sounds like you want to work with the same document, but change its contents, using the set(...) method. Something like this:

Map<String, Object> city = new HashMap<>();
city.put("name", "Los Angeles");
city.put("state", "CA");
city.put("country", "USA");

db.collection("cities").document("LA").set(city)

(This example is coming from the Firestore docs -- https://firebase.google.com/docs/firestore/manage-data/add-data )

In your case, you might want a Map<String,Integer> of bird names to counts (of those birds), and do:

db.collection("counters").document("birds").set(birdCountMap)

Later on, if you need to update a value, you COULD change the map object and call set() again, but it might be more efficient (e.g., if you had thousands of birds?) to use the update() method to update a single field in the document, instead of sending the whole document. See, later on the docs page: https://firebase.google.com/docs/firestore/manage-data/add-data#update-data

There may be other better ways of structuring the data... I would have to think about it, but this is one way that should work!

answered by (508 points)
...