swift - @ServerTimestamp 是否可以在 Firestore 中设置一次,并在更新时跳过
问题描述
我想同时拥有createdAt
和lastUpdatedAt
字段,这两个字段都应该由服务器设置。
为了保持一致,我想我会创建一个包装器,它总是将这些支持属性设置为所有文档:
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
我的设置中的字段的情况下更新?
解决方案
不幸的是,这在服务器上是不可能直接实现的。虽然您可以拒绝覆盖createdAt
, 并且可以要求lastUpdatedAt
在安全规则中存在 , 但无法忽略写入指令中传递的值。
这意味着您有一种情况,您要写入文档的数据取决于该文档中的现有数据,您将需要使用事务。
推荐阅读
- linux - 尝试使用 npx 创建反应应用程序时收到各种警告和错误
- html - overflow-x 滚动显示:flex,最后一个子项不显示父 div 填充和边距
- docker - Dockerfile 正确构建但 ADD 失败
- system-verilog - 在 Specman E 中实现 System verilog 的 $value$plusargs() 系统函数
- javascript - 在javascript中将图像从一个页面显示到另一个页面,而不发送所有div
- javascript - 开玩笑地模拟获取响应的 blob 的 fetch() 函数
- excel - Excel 数据整合
- android - 在 android studio 3.4.2 中导入约束布局时无法解析符号
- visual-studio-code - 有人能告诉我 Visual Studio Code 中使用的是什么字体吗?
- go - 如何从 golang 项目文件中获取图像路径