sicilian_bum
sicilian_bum

Reputation: 19

How to update document in firestore using collection reference?

I'm having a problem in updating my document using collection reference in firestore android. It is auto-generated id so I don't even know what is the id of my document.

Upvotes: 0

Views: 988

Answers (1)

gilokimu
gilokimu

Reputation: 531

Save the id when retrieving the data eg

db.collection("cities")
    .whereEqualTo("capital", true)
    .get()
    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    City city = document.toObject(City.class);

                    city.setId(document.getId()); //This is what you are looking for

                    ...

                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

You can that when updating

city.setName("LA"); //edit object
db.collection("cities").document(city.id).set(city); //save object

PS I have not run this code - could have syntax errors, careful not to copy paste.

Upvotes: 1

Related Questions