Firestore: Updating field in an object removes previous field

2,586

To update 'a_numbers' with Pair without removing the previous values, you should assign the reference path (example: 'a_number.2222') to K and assign value to V. I edited your code. please review it for more information.

DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
ref.updateData({'a_numbers.2222': value});
Share:
2,586
Admin
Author by

Admin

Updated on December 06, 2022

Comments

  • Admin
    Admin 15 minutes

    I am using Flutter cloud firestore. Here is how my database looks like.

    enter image description here

    I want to add more fields (like "2222") in a_numbers object. I use updateData()like this,

    DocumentReference ref = Firestore.instance.document("products/-LMhR5cAyW4T0sa03UtU");
    ref.updateData({"a_numbers": {"2222" : false}});
    

    The above snippet basically deletes the previous value (1111) and then updates the database with 2222 field.

    Any solution?

  • Admin
    Admin about 4 years
    You mean first I need to retrieve all the data (in form of map) and then use updateData() method? In this case what is the use of using updateData(), you can use setData() too. And also you would have lots of read write operation just to add one field. Not good in my opinion.
  • Shady Aziza
    Shady Aziza about 4 years
    this is because the way you structured your data, update data will only work on the first class fields inside of a document, that is the very first tree of fields under the document so it will update just these fields without the need to overwrite, however you are updating a nested field so you need to store the current value, append on it then update. it is just the way updating a doc in firestore works, it only updates the top level fields in the doc
  • Admin
    Admin about 4 years
    I found a solution but that only works in Android (native), the Firebase team will definitely find out a solution for this. Please see this answer, there is SetOptions class that Flutter is missing. Otherwise everything works fine.