首页 > 解决方案 > @ServerTimestamp 是否可以在 Firestore 中设置一次,并在更新时跳过

问题描述

我想同时拥有createdAtlastUpdatedAt字段,这两个字段都应该由服务器设置。

为了保持一致,我想我会创建一个包装器,它总是将这些支持属性设置为所有文档:

struct FIRDocument<T: Codable>: Codable {
   let data: T
   @ServerTimestamp var createdAt: Timestamp? = nil
   @ServerTimestamp var lastUpdatedAt: Timestamp? = nil
}

并像这样使用它:

struct Message: Codable {
   content: String
}

let ref = firestore.collection("messages").document()

// later
let newDoc = FIRDocument(data: Message(content: "hello"))
ref.addDocument(from: newDoc) { ... }

// later yet
let updatedDoc = FIRDocument(data: Message(content: "goodbye"))
ref.setData(from: updatedDoc) { ... }

显然,上面的代码只是更新了两个时间戳。有没有办法在lastUpdatedAt不重置createdAt我的设置中的字段的情况下更新?

标签: swiftgoogle-cloud-firestore

解决方案


不幸的是,这在服务器上是不可能直接实现的。虽然您可以拒绝覆盖createdAt, 并且可以要求lastUpdatedAt在安全规则中存在 , 但无法忽略写入指令中传递的值。

这意味着您有一种情况,您要写入文档的数据取决于该文档中的现有数据,您将需要使用事务


推荐阅读