0

enter image description here

I have a document in Firebase Firestore like the above picture, i want to modify a single element in "order" array, i know there is no direct way to do it but is there any way?

i tryed the below code

    let ww = db.collection("collectionName").document("docName")

    let arrayElement = 0
    ww.updateData([
                           "order.\(arrayElement).isHasOffer": true,
                           "order.\(arrayElement).referenceID": self.referenceID,
                           "order.\(arrayElement).DosageForm": "dd",
                           "order.\(arrayElement).GenericName": "test",
                           "order.\(arrayElement).DISC": 33
                           ]) { err in
                               if let err = err {
                                   print("Error updating document: \(err)")
                               } else {
                                   print("Document successfully updated")
                               }
                           }

it's override "order" array (remove all the element and adding only what i pass in the code) -> what if there is 100 elements? should i rewrite them all again

it's also convert it from "Array" type to "map", once converted to "map" i'm not able to read them back as an array

note: i have a unique id for every element in the array

OneOfThem
  • 23
  • 6

1 Answers1

2

Whenever you want to modify individual elements of an array type field, you have to read the document, modify the array in memory, then update the modified array back to the document.

You will not be able to do this without reading the document first. If you require an atomic update, you can perform this read-then-update procedure in a transaction.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Hi oneOfThem. Did you find a solution to this? I'm currently facing a problem on this exact part right now – Kelly Dec 20 '21 at 18:06