Ali Nabel
Ali Nabel

Reputation: 196

updating Map values in array flutter Firebase

here is the map and the vlaue im trying to update enter image description here

the problem is when i try to update the imageUrl , the whole Map replacing with only ImageUrl new value like this enter image description here

what i want is to update imageUrl only , not effecting other data

this is what i do but not work

FirebaseFirestore.instance.collection('oorders').doc('MyDocId')
                                 .update({ 'items.0.imageUrl'    :  'new image Url' });

Upvotes: 0

Views: 1693

Answers (1)

Prabir
Prabir

Reputation: 1586

From the provided Firestore Database structure it is clear that you are trying to update an element inside an array field in a Firestore document. But currently Firestore doesn't have the ability to update an existing element in an indexed array. It supports only two methods, arrayUnion() to add an element and arrayRemove() to remove an element from the array as mentioned in the documentation.

So if you try to do something like the following -

FirebaseFirestore.instance
    .collection('oorders')
    .doc('MyDocId')
    .update({'items.0.imageUrl': 'new image Url'});

it will delete the array element items and create another map named items with the field mentioned in the update statement.

As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely. This is an error prone and tedious process. You can have a look at this article to know more about it.

I am not sure of your use case, but it seems you can make your database structure more suitable by using maps(nested objects) instead of arrays. Something like this -

enter image description here

By doing this you can update the nested objects by dot notation as mentioned here which will update only the mentioned field without deleting the other fields. The sample to update the document will look like this -

   var item = 'item1';
   var propertyToBeUpdated = 'imageUrl';
   var newImageUrl = 'New image Url';
   FirebaseFirestore.instance
       .collection('collectionId')
       .doc('documentId')
       .update({'items.$item.$propertyToBeUpdated': newImageUrl});

Upvotes: 2

Related Questions