首页 > 解决方案 > 是否可以同时为 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()
      });
    });
  });
});

}

标签: firebasegoogle-cloud-firestoretransactionsfirebase-storagefile-storage

解决方案


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

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


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


推荐阅读