I am learning Firebase and now I want to store my dummy data to Firebase collection,
I have a model class TransactionCategory which has three fields
- id 2. name 3. array of transactions
like TransactionCategory(id:’1′,name:’Shopping’,transactions:[])
here I want to make a collection "Transaction Category" and instead of storing transactions in a field I want it to store inside a child collection named ‘Transactions’
hope I am clear in explaining what I want…
Parent Collection : TransactionCategory and it has two field(id,name) and a child collection(transactions)
List<TransactionCategory> transactionCategoryList = [
TransactionCategory(id: '1', name: 'Food',
//this array should be store in child collection
transactions: [
Transaction(id: '1', title: 'Dinner', amount: 100),
Transaction(id: '2', title: 'Breakfast', amount: 30),
Transaction(id: '3', title: 'Dinner', amount: 230),
]),
TransactionCategory(id: '2', name: 'General',
//this array should be store in child collection
transactions: [
Transaction(id: '1', title: 'Milk', amount: 50),
Transaction(id: '3', title: 'Detergent', amount: 299),
]),
TransactionCategory(id: '3', name: 'Shopping', transactions:
//this array should be store in child collection
[
Transaction(id: '1', title: 'Clothe', amount: 3000),
Transaction(id: '2', title: 'Shoes', amount: 1200),
Transaction(id: '3', title: 'Shoes', amount: 2200),
]),
];
Button(
title: 'save Categories',
onPressed: () async {
//for saving transaction list into a child collection
final _db = FirebaseFirestore.instance;
//here i dont know what should i code
},
),
I want to save dummy data like this format shown in image
2
Answers
According to your last comment, if you want to add a new document inside the "Transactions" sub-collection, then you have to create a reference that points to the sub-collection:
Now you can use this collection reference to add documents.
If you want to add a new document inside the "TransactionCategory" sub-collection, then refer to this code