【发布时间】: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