How to monitor entire subcollection using transact

2019-08-24 09:07发布

问题:

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

                });

How to solve?

Thanks!

UPDATE:

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

回答1:

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.

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.