Reputation: 142
I am making an simple currency reminder app where I am supposed to note down the money I receive from other user or I gave other user money as a reminder so as to not forget it. And while creating a subcollection for each Collection's document, I think there is a problem.
The code for adding the received data into firebase is as follows:
onPressed: () async{
Map<String, dynamic> mapdata = {
'amount':_amountreceivedcontroller.text,
'details': _detailsreceivedcontroller.text,
};
var collectiondata = await FirebaseFirestore.instance.collection('LoanFriends');
var querySnapshots = await collectiondata.get();
for(var snapshot in querySnapshots.docs){
var documentID = snapshot.id;
await FirebaseFirestore.instance.collection('LoanFriends').doc(documentID).collection('ReceivedLoanData').add(mapdata);
}
_amountreceivedcontroller.text = '';
_detailsreceivedcontroller.text = '';
Navigator.pop(context);
},
Upvotes: 1
Views: 215
Reputation: 4854
Because you are looping through querySnapshots and updating each and every document you have inside LoanFriends collection. So just use an if condition to add data to a specific friend.
onPressed: () async{
Map<String, dynamic> mapdata = {
'amount':_amountreceivedcontroller.text,
'details': _detailsreceivedcontroller.text,
};
//Friend you lend money
var frined = _friendController.text;
var collectiondata = await FirebaseFirestore.instance.collection('LoanFriends');
var querySnapshots = await collectiondata.get();
for(var snapshot in querySnapshots.docs){
var documentID = snapshot.id;
//for the specific document associated with your friend
if(snapshot.name==friend){
//add lended money details and break loop
await collectiondata.doc(documentID).collection('ReceivedLoanData').add(mapdata);
break;
}
}
_amountreceivedcontroller.text = '';
_detailsreceivedcontroller.text = '';
_friendController.text = '';
Navigator.pop(context);
}
You can also query your firestore collections
onPressed: () async{
Map<String, dynamic> mapdata = {
'amount':_amountreceivedcontroller.text,
'details': _detailsreceivedcontroller.text,
};
//Friend you lend money
var frined = _friendController.text;
var collectiondata = await FirebaseFirestore.instance.collection('LoanFriends');
//directly query your database with friend name and get specific document
var query = collectiondata.where("name", '==', friend);
var snapshot = await query.get();
//add lended money details
await snapshot.collection('ReceivedLoanData').add(mapdata);
_amountreceivedcontroller.text = '';
_detailsreceivedcontroller.text = '';
_friendController.text = '';
Navigator.pop(context);
}
Upvotes: 1