0
votes

Within my Flutter App, I would like to allow a signed in user to be able to read the document/s that were created by them (Only If the DocumentID is same as UserID). The problem is that the documentID is generated by firebase automatically. when I explicitly specify the documentID using the signed in UserID, the user is not able to create more than one document because the documentID already exists. Please help...

The result is always showing the snapshot error below...

StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('orders').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else {
            if (snapshot.hasError) {
              return const Center(
                child: Text('Oops, something went wrong...'),
              );
            }
          }

Adding Data to Firestore

onPressed: () {
                  var firebaseUser = FirebaseAuth.instance.currentUser;

                  FirebaseFirestore.instance.collection('orders').add({
                    'date': FieldValue.serverTimestamp(),
                    'product': 'Jeans',
                    'total': cart.totalAmount,
                    'uid': firebaseUser!.uid,
                  });
                  cart.clearCart();
                },

Displaying data from Firestore

StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection('orders').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else {
            if (snapshot.hasError) {
              return const Center(
                child: Text('Oops, something went wrong...'),
              );
            }
          }

Security Rules

enter image description here

enter image description here

2
If you want to create a document that has the same ID as the signed in user's ID then yes you will only be able to make one document as the user's ID is not changing. To get around this you would have to delete the old document before creating a new one. Or allow the order document ID to be generated and just hold the user's ID on that document so you would be able to query "for all orders where userID is currentUser.id" - Amxela
Hi @Amxela, thanks for the prompt response. I guess I will have to query all orders where the UserID is currentUserID. - supremo
Everything related to firebase firestore and flutter can be found here firebase.flutter.dev/docs/firestore/usage querying specifically is here firebase.flutter.dev/docs/firestore/usage/#querying - Amxela
Thanks, I'm on it... - supremo

2 Answers

1
votes

If you want a user to be able to create multiple documents, you can't use their UID as the document ID - as document IDs are unique within a collection.

The common approach is to use add() document to let Firestore generate a unique document ID, and then store the UID of the user in a field in each document (as you already seem to do).

You can then enforce that the user can only write a document that contains their own UID in security rules by also calling your isOwner helper function in the write rule:

allow write: if request.auth != null && isOwner();
0
votes

To get the documentId while adding data in database:

DocumentReference docRef = _firestore.collection("orders").doc();

             await docRef.set({
                'id': docRef.id,
                'date': FieldValue.serverTimestamp(),
                'product': 'Jeans',
                'total': cart.totalAmount,
                'uid': firebaseUser!.uid,
              });