Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update array elements in Firestore with Android?

I read this post and this post of the same guy saying that you cannot update array elements.

I also read a recent article, where is says that this can be done somehow with arrayUnion or something like that but I cannot get any informations on stackoverflow either in the docs.

Is there any way I can solve this? Thanks!

like image 235
Alex _Favaro_ Avatar asked Sep 12 '18 13:09

Alex _Favaro_


People also ask

How do I update my firestore data?

Firestore Update Entire DocumentgetDatabase() → where we want to update a document. doc() → where we'll be passing references of database, collection and ID of a document that we want to update. setDoc() → where we actually pass new data that we want to replace along with the doc() method.


1 Answers

Actually, the "guy" who wrote those answers it's me :) At that time, there wasn't a way in which you could update array elements. It was possible only to store arrays but not to update array members.

Now, when updating a document, you can pass as the second argument to the update() method:

FieldValue.arrayUnion("newArrayValue")

You can find more informations in the official documentation regarding update elements in an array.

If your document contains an array field, you can use arrayUnion() and arrayRemove() to add and remove elements. arrayUnion() adds elements to an array but only elements not already present. arrayRemove() removes all instances of each given element.

P.S. I will also update those answers.

like image 200
Alex Mamo Avatar answered Nov 15 '22 00:11

Alex Mamo