【问题标题】:Is it possible to run Transactions and batched writes for Firestore and Firebase-Storage simultaneously?是否可以同时为 Firestore 和 Firebase-Storage 运行事务和批量写入?
【发布时间】:2020-08-09 19:02:18
【问题描述】:

用例:我必须在 document_2 中写入一些 document_1 更新并删除 document_3 并删除file_4 来自 file_storage,使用单个事务,使用事务和批量写入。可能吗?如果可能怎么办?

注意:完成时所有四个异步任务都应该成功,或者所有四个任务都应该失败。如果案例是读写的,只有这个Transactions and batched writes documentation 可以提供帮助。但在我们的例子中,还有文件读取-上传-删除任务。

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()
      });
    });
  });
});

}

【问题讨论】:

    标签: firebase google-cloud-firestore transactions firebase-storage file-storage


    【解决方案1】:

    在撰写本文时,您不能将对 Firestore 的写入操作与对 Cloud Storage 的写入操作包含在一个原子操作中。

    正如您所提到的,您可以在 Firestore 中为您的写入/更新/删除操作使用批量写入,这将是原子的,但您不能将写入包含到存储中。


    您可以构建自己的机制,定期检查 Cloud Storage 中的每个文件在 Firestore 中是否有相应的配置(文档已正确更新、删除等),反之亦然。只是一个(非常)hacky解决方法的建议......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-26
      • 2018-08-03
      • 2021-12-25
      • 1970-01-01
      • 2022-01-25
      • 2019-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多