Trevor
Trevor

Reputation: 843

Swift Firestore update field value in array of custom model

enter image description here

I am trying to update the field "voteCount" inside of the eventContents array of eventContent.

here is the model:

struct EventContent: Identifiable, Codable, Hashable {
    var id: String?
    var url: String?
    var data: Data?
    var isVideo: Bool?
    var voteCount: Int?
    var userFullName: String?
    
    private enum EventContent: String, CodingKey {
        case id
        case imageURL
        case data
        case isVideo
        case voteCount
        case userFullName
    }
}

I know how to update the array of eventContents itself using updateData and FieldValue.arrayUnion - however, this updates the entire eventContent. How can I only update the "voteCount" field inside of my array of custom model?

Upvotes: 0

Views: 1228

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

There is no way within the Firestore API to update an existing item in an array atomically. You'll have to first read the document from the database, update the array in your application code, and then write it back.

Alternatively you can create a field that maps the uses the even ID as its key, and then update just the voteCount under that with:

db.collection("EventsData").document("5Ag9...").updateData([
    "2F27B92...5989B.voteCount": FieldValue.increment(Int64(1))
]

Also see the documentation on updating nested objects, atomic increments and these previous questions on the topic:

Upvotes: 1

Related Questions