Reputation: 23
I am trying to add key value pairs to a map of maps in a firestore document. You can see the document set up below. The "Bills" map consists of key value pairs representing each bill. Each bill is represented by a map. For example: "Bill 1" consists of key value pairs which represent the name of the item and the cost of the item.
I want to add key value pairs to the bill. For example, I want to add an item to "Bill 1", so that it consists of both "Bacon: 14" and the other items I add.
Here is the code I have right now. However, this code simply replaces Bacon with the new item I add. It doesn't add the new value to the existing map, simply replaces the entire map (the contents of Bill 1) with the new item and cost.
Here is the current code:
static Future addItemToBill(GroceryItem groceryItem, double cost) async {
try{
final FirebaseUser currentUser = await FirebaseAuth.instance.currentUser();
int currentBillNumber = await getBillCount(currentUser.uid);
if(currentBillNumber == 0){
currentBillNumber = 1;
}
final DocumentReference documentReference = usersCollection.document(currentUser.uid);
await documentReference.updateData({
"Bills.Bill $currentBillNumber": {
"${groceryItem.itemName}" : cost
}
});
}catch(error){
}
}
Thank you for the help!
Upvotes: 2
Views: 4585
Reputation: 26
What about having all bills
as a new, highest level, collection and then use the userUID
as a key in each bill document?
Then, if you want all the bills for a single user:
db.collection('allBills').
.whereEqualTo("userUID", currentUser.uid)
.get()
Less nesting of collections and documents.
Upvotes: 0
Reputation: 317808
When you call updateData, Firestore will always replace everything behind each key you provide. In your case, the key is "Bills/Bill $currentBillNumber", and it will contain only what you provide, replacing what's already there at the given key.
If you want to add something new, your will will have to be specific enough that it does not replace other values.
await documentReference.updateData({
"Bills.Bill $currentBillNumber.${groceryItem.itemName}": cost
});
Upvotes: 4
Reputation: 3072
I guess could be better you create a collection of bills inside of each user, then you will have a collection of documents (bills), inside of each document (bill) you create another collection called items and then ou will have a list of documents (items), will be easy to query later i think.
You should have like this:
-collection(users)
--document(user)
---collection(bills)
----document(bill)
-----collection(items)
------document(item)
Got it?
Upvotes: 1