Per the new Firestore documentation, I see 2 new methods (arrayUnion, arrayRemove) for working with arrays nested within documents. These methods allow you to add and remove an array item, but how would I update an existing element?
-
Pretty sure theres not update build-in function, in that case you need to remove, edit and add again. – Karlo A. López Dec 12 '18 at 20:37
2 Answers
There is no update method because if you want to perform an update, you need to know the index of that particular element. When talking about Cloud Firestore arrays, things are different than you might think.
Because we are creating apps that can be used in a multi-user environment, try to think what might happen if a user wants to edit a value at index 0, some other user wants to delete the value at index 0 and in the same time some other user might want to add another item at index 0. For sure, you'll end up having very different results and why not, get even an ArrayIndexOutOfBoundsException. So Firestore actions with arrays are a little bit different. So you cannot perform actions like, insert, update or delete at a specific index.
As Doug mentioned in his answer, if those two methods do not help you enough, you should get the entire document, get the array, modify it and add it back to the database.

- 130,605
- 17
- 163
- 193
If your array modification is not satisfied by arrayUnion or arrayRemove, you will have to read the document, modify the array values in memory, then update the array field with the new array in its entirety.

- 297,357
- 32
- 422
- 441
-
I have an array of maps. So I was hoping I could just update one item of the array (which is a map) with all the key value pairs for that particular array item. But it sounds like I will basically need to get all array items and rebuild the entire array to update one element with the map values that have changed. – Jim Jones Dec 13 '18 at 01:02
-
-
1@JimJones It seems you can also delete the item assuming you can recreate the exact object, then add the "updated" object inside of your array. It's expensive, but possible. – ntgCleaner Jul 26 '19 at 20:29