firebase - 是否可以同时为 Firestore 和 Firebase-Storage 运行事务和批量写入?
问题描述
用例:我必须在document_2中写入一些document_1更新,并使用 Transactions 和批量写入的单个事务从 file_storage 中删除document_3和删除file_4 。可能吗?如果可能怎么办?
注意:完成时所有四个异步任务都应该成功,或者所有四个任务都应该失败。如果案例是读写的,那么只有这个Transactions and batched writes 文档可以提供帮助。但在我们的例子中,也有文件读取-上传-删除任务。
Future<void> _runTransaction() async {
firestore.runTransaction((Transaction transaction) async {
final allDocs = await firestore.collection("messages").getDocuments();
final toBeRetrieved =
allDocs.documents.sublist(allDocs.documents.length ~/ 2);
final toBeDeleted =
allDocs.documents.sublist(0, allDocs.documents.length ~/ 2);
await Future.forEach(toBeDeleted, (DocumentSnapshot snapshot) async {
await transaction.delete(snapshot.reference);
});
await Future.forEach(toBeRetrieved, (DocumentSnapshot snapshot) async {
await transaction.update(snapshot.reference, {
"message": "Updated from Transaction",
"created_at": FieldValue.serverTimestamp()
});
});
});
await Future.forEach(List.generate(2, (index) => index), (item) async {
await firestore.runTransaction((Transaction transaction) async {
await Future.forEach(List.generate(10, (index) => index), (item) async {
await transaction.set(firestore.collection("messages").document(), {
"message": "Created from Transaction $item",
"created_at": FieldValue.serverTimestamp()
});
});
});
});
}
解决方案
在撰写本文时,您不能在一个原子操作中包含对 Firestore 的写入操作和对 Cloud Storage 的写入操作。
正如您所提到的,您可以在 Firestore 中为您的写入/更新/删除操作使用批量写入,这将是原子的,但您不能包含对存储的写入。
您可以建立自己的机制,定期检查 Cloud Storage 中的每个文件在 Firestore 中是否有相应的配置(文档已正确更新、删除等),反之亦然。只是一个(非常)hacky解决方法的建议......
推荐阅读
- android - 如何在 Android 中使用 Proto Data Store 准备 proto 文件和更新数据?
- mfc - 使用 UTF-8 代码页时 MFC 中的自动换行问题
- r - 如果输入已更改,如何根据先前的输入值停止计算?
- python - 如何在 Python 中使用 OpenCV houghcircles() 输出数组参数
- c++ - C++ 获取非静态函数的地址
- c# - 在 .NET 5 中导出 DER 公钥
- android - 如何获取子集合中文档的ID?
- drupal - Drupal 8 中未显示的模块
- python - 使用熊猫重新排列表格
- memory - COW 和 Demand 分页一样吗?