I'm trying to update an index inside an array that I have stored in Firestore, but when I pass the parameter it deletes everything and leaves me what I just added instead of updating that field, can you tell me what I'm doing wrong?
I would like to update, for example, inside the hoursList array, index 0, the field called "available". I have tried with this:
firebaseFirestore.collection(APPOINTMENTS_PATH).document(selectedDay)
.update(mapOf(
"hourList.0.available" to false
))
Firestore arrays don't support index-based operations due to the concurrency problems it might cause.
Imagine that you send a request to modify the element that is at index 1, and at that moment another user deletes the first element of the array. Now the element you wanted to modify was left in place 0, so the request you sent would end up modifying an element that was not the one you wanted.
To avoid this, they decided that the arrays would behave like what we know in kotlin as
Set
. The modification operations it supports areFieldValue.arrayUnion()
andFieldValue.arrayRemove()
and the query operations arewhereArrayContains()
andwhereArrayContainsAny()
.There is a way to "modify" an element of an array without using indexes, but it's actually removing the current element and creating a new one with the updated data:
This option is not recommended because you can run into problems if multiple users try to modify the document at the same time. In addition, you must send all fields of the map, which translates into a waste of bandwidth. Of course the new element will not have the same index as the one you removed but will be added to the end of the list.
For all this , it is NOT recommended to use arrays in cases like yours. Instead you can replace it with a map or with separate documents in a subcollection. The syntax you used would work just fine in a map.