【发布时间】:2019-07-18 21:13:55
【问题描述】:
关注answer 我正在尝试使用事务来监控整个 Firestore 子集合以添加新文档。基本上,如果只有一个文档,我只想将新文档写入子集合。我需要使用事务来避免竞争条件导致子集合中 >2 个文档。最大值应为 2。
如何使用事务来监控添加到子集合的文档?
我尝试了很长时间但无法解决。
我正在实验使用迭代文档的子集合,但不知道如何通过事务来做到这一点。
到目前为止我的代码(可能是错误的方法):
Firestore.instance.runTransaction((transaction) async {
final CollectionReference collectionRef = ref
.document(‘document’).collection(‘subCollection’);
List<DocumentSnapshot> subCollectionDocsSnapshot = [];
await collectionRef.getDocuments().then((querySnapshot) =>
querySnapshot.documents.forEach((document) {
subCollectionDocsSnapshot.add(document);
}
));
final DocumentReference newDocRef = collectionRef.document(docName);
await transaction.set(
newDocRef,
{‘docName’: docName,
}
);
});
如何解决?
谢谢!
更新:
我也尝试添加 transaction.get() 以遍历子集合文档,但它对竞争条件没有影响:
subCollectionDocsSnapshot.forEach((document) {
transaction.get(document.reference);
});
【问题讨论】:
标签: firebase dart transactions flutter google-cloud-firestore