[英]Swift Firestore update field value in array of custom model
我正在尝试更新 eventContent 的 eventContents 数组中的字段“voteCount”。
这是 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
}
}
我知道如何使用 updateData 和 FieldValue.arrayUnion 更新 eventContents 本身的数组 - 但是,这会更新整个 eventContent。 我怎样才能只更新自定义 model 数组中的“voteCount”字段?
在 Firestore API 中无法以原子方式更新数组中的现有项。 您必须先从数据库中读取文档,更新应用程序代码中的数组,然后再将其写回。
或者,您可以创建一个映射使用偶数 ID 作为其键的字段,然后仅更新该字段下的voteCount
:
db.collection("EventsData").document("5Ag9...").updateData([
"2F27B92...5989B.voteCount": FieldValue.increment(Int64(1))
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.