objective-c - Firebase 多集合更新
问题描述
有没有办法在一个请求中更新两个文档,每个文档都在不同的集合中?
我知道您可以使用批量写入FIRWriteBatch
- 这似乎仅限于任何文档更新的同一集合。尝试为两个不同集合中的文档附加更新时:
// Just for example
FIRWriteBatch *batch = FIRWriteBatch.new;
[batch updateData:@{@"posts" : @1} forDocument:[self.firebase.usersCollection documentWithPath:@"some_user_id"]];
[batch setData:@{@"test" : @"cool"} forDocument:[self.firebase.postsCollection documentWithPath:@"some_post_id"]];
[batch commitWithCompletion:^(NSError * _Nullable error) {
NSLog(@"error: %@", error.localizedDescription);
}];
它永远不会执行 - 应用程序崩溃,我得到了这个:
Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason:
'Provided document reference is from a different Firestore instance.'
显然,该批次不喜欢多个集合中的更新。
- 有谁知道如何更新两个文档,每个文档都在不同的集合中,而一个失败而另一个成功?
例如,我想避免在 usersCollection 中成功设置文档posts = 1
,而在postsCollection中编写新文档失败。
我知道一个人写而另一个人失败是不太可能的,但如果确实发生了,我显然不想要不一致的数据。
笔记:
对于任何关心的人 - 我不知道它是否会失败,但到目前为止,我在更新数据之前没有阅读文档就运行事务...... ♂️ 为 -1 API 调用干杯!
解决方案
您应该使用事务,它记录在批处理写入旁边:
Using the Cloud Firestore client libraries, you can group multiple operations into a single transaction. Transactions are useful when you want to update a field's value based on its current value, or the value of some other field. You could increment a counter by creating a transaction that reads the current value of the counter, increments it, and writes the new value to Cloud Firestore.
You are not limited to a single collection when performing a transaction. You are just obliged to read the document before you write it:
A transaction consists of any number of get() operations followed by any number of write operations such as set(), update(), or delete(). In the case of a concurrent edit, Cloud Firestore runs the entire transaction again. For example, if a transaction reads documents and another client modifies any of those documents, Cloud Firestore retries the transaction. This feature ensures that the transaction runs on up-to-date and consistent data.
推荐阅读
- r - 将数据除以前一行并创建新的数据框
- javascript - 使用在页面加载时替换的无效 HTML
- xaml - Xamarin 形成日期时间选择器
- css - 在 Bootstrap 中定位单选按钮
- jquery - 在 cakephp 中有 1 个按钮用于保存和调用 JS 函数
- javascript - 使用 Datepicker 选择日期然后显示日期减去一天
- python - 有什么理由我的温度列表不允许我检查上限和下限?
- heroku - Puppeteer 的 uploadFile 如何在 Heroku 上工作?
- sqlite - 在 SwiftUI 中使用外部 SQLite 数据库
- java - 由于依赖项 xerces:xercesImpl:jar:2.9.1,Grails 运行应用程序失败