如何使用事务监视整个子集合? [英] How to monitor entire subcollection using transaction?
问题描述
按照此 answer 的操作,我尝试使用事务来实现,以监视整个Firestore子集合中是否添加了新文档。基本上,如果只有一个文档,我只想将新文档写入子集合。我需要使用事务来避免争用情况导致子集合中的文档> 2。最大值应为2。
Follow this answer I am try to implement using transaction to monitor entire Firestore subcollection for new document added. Basically I only want write new document to subcollection if there is only one document. I need use transaction to avoid race condition resulting in >2 document in subcollection. Max should be 2.
如何使用事务监视添加到子集合中的文档?
How to use transaction to monitor document added to subcollection?
我很努力是时候去做,但是无法解决。
I am try long time to do but cannot solve.
我正在实验通过子集合对文档进行迭代,但是不知道如何通过事务来完成。
I am experiment use iterate through subcollection for document but not know how to do this through transaction.
到目前为止我的代码(可能是错误的方法):
My code so far (maybe wrong method):
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()
遍历子集合文档,但对竞争条件没有影响:
I have try add also transaction.get()
to iterate through subcollection docs but it have no effect on race condition:
subCollectionDocsSnapshot.forEach((document) {
transaction.get(document.reference);
});
推荐答案
Firestore交易不支持此功能。在事务中,您只能按其ID查找文档。您无法处理集合的全部内容,并且如果在交易过程中添加了新文档,则必须重试该交易。您也不能根据查询的结果进行交易。
This isn't supported by Firestore transactions. Within a transaction, you can only find a document by its ID. You can't transact on the entire contents of a collection, and have that transaction retry if an new document is added while in the middle of the transaction. You also can't transact on the results of a query.
相反,请考虑在另一个集合中计算一个集合中的文档数来使用另一个文档,然后使用在您的交易中。或者至少是一个记录布尔值的文档,该布尔值指示集合中是否包含> 2个文档。
Instead, consider having a different document in another collection that counts the number of documents in a collection, and use that in your transaction. Or, at the very least, a document that records a boolean indicating whether or not the collection has >2 documents.
这篇关于如何使用事务监视整个子集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!