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
CodePudding user response:
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();
CodePudding user response:
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,
});