OneOfThem
OneOfThem

Reputation: 23

Firestore Update single item in array of objects

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

Upvotes: 0

Views: 2634

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317928

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.

Upvotes: 2

Related Questions