Firestore batch completes even when arrayRemove() operation in the batch fails to succeed

Viewed 44

I'm attempting to update a nested object within a Firestore array. This requires that the original object is removed from the array using arrayRemove() and the updated object is added using arrayUnion(). These two operations are made within a batch to ensure they both occur, with the expectation that the batch will fail if either of the operations fails. Here is some sample code using Swift:

let batch = db.batch()
         
let docRef = db.collection("events").document("20220715")
let encodedRemove = try! Firestore.Encoder().encode(originalEvent)
let encodedUpdate = try! Firestore.Encoder().encode(updatedEvent)

batch.updateData(["dayEvent": FieldValue.arrayRemove([encodedRemove])], forDocument: docRef)
batch.updateData(["dayEvent": FieldValue.arrayUnion([encodedUpdate])], forDocument: docRef)

batch.commit() { err in
    if let err = err {
        print("Error writing batch \(err)")
    } else {
        print("Batch write succeeded.")
    }
}

This works as expected when making an update. The value of the original object is stored locally to pass to arrayRemove() and a new object is created for the update to pass to arrayUnion(). The batch is then passed to Firestore which removes the original object and adds the updated object.

However, if the original object is modified on then server after it has been stored locally, the batch still succeeds without removing the original object using arrayRemove(). Since the object has changed on the server, I'd expect the arrayRemove() call to fail since there is no longer a match for the object to remove from the array. However, arrayRemove() seems to silently fail in the batch--the array object is not removed, but the updated object is added to the array. In turn, this leave 2 objects in different states within the array.

Why is the batch operation still completing even though arrayRemove() operation has failed? As highlighted in the docs, in a batch operation, "either all of the operations succeed, or none of them are applied."

https://firebase.google.com/docs/firestore/manage-data/transactions#batched-writes

0 Answers
Related