7

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!

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Alex _Favaro_
  • 89
  • 1
  • 4
  • 2
    Check this link : https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array [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. – Ashish Das Sep 12 '18 at 13:36
  • 2
    Welcome to StackOverflow, even thought providing links into questions is good to explain the issue you are facing, it is still recommended for you to give some more background and explanation about the issue you are trying to resolve. – smn.tino Sep 12 '18 at 13:36
  • Hmm, already having answer for your question in this link https://stackoverflow.com/questions/46757614/how-to-update-an-array-of-objects-with-firestore/ – Ashish Das Sep 12 '18 at 13:46
  • @AshishDas Thanks but I'm looking for Android, that answer provides a solution in Javascript and do not understand. – Alex _Favaro_ Sep 12 '18 at 13:51
  • @smn.tino I need to know if this is possible, so I can use this feature in my project or not and I understand is possible. Thanks anyway. – Alex _Favaro_ Sep 12 '18 at 13:52

2 Answers2

15

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

Try using FieldValue.arrayUnion(comment_full) instead of passing comment_full FirebaseFirestore.getInstance().collection("posts").document("$postid").update("comments",FieldValue.arrayUnion(comment_full))