0

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?

Trevor
  • 580
  • 5
  • 16
  • 1
    Possible solution: Instead of putting eventContents inside of the document I will create a new collection inside of each event ("5Ag92.." is shown in image), and each eventContent can have its own document of fields – Trevor Mar 15 '22 at 21:44
  • Since Swift is almost similar to Kotlin, I think that this [article](https://medium.com/firebase-tips-tricks/how-to-update-an-array-of-objects-in-firestore-cdb611a56073) will help. – Alex Mamo Mar 16 '22 at 11:10

1 Answers1

1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • It seems more efficient to move my array of eventContent into a sub collection of each event. ("5ag9.."). Also would allow me to only get the eventContent data when needed instead of getting it everytime I call the 5ag9.. doc – Trevor Mar 15 '22 at 23:00
  • Yeah, that would work too. – Frank van Puffelen Mar 16 '22 at 03:34