Devarsh Ranpara
Devarsh Ranpara

Reputation: 1112

Firebase : Manage one to many relationship in Cloud Firestore

I am developing one application to manage a basic account, which has Firebase as a backend. But in the Firestore structure, I am a bit confused that how should I manage transactions for account in Cloud Firestore.

As I am coming from a SQL background, I am very confused to do so.

For one account I will have many transactions containing credit or debit data.

Can anyone suggest me some basic and effective way to implement this?

This is my existing implementation but, for every account, I want to add transaction.

By transactions I mean just like bank transactions, just as your passbook.

I want to add the above data in the transaction.

amount -> how much amount I have credited/debited

date -> credit/debit date

details -> date of transaction

is_credit -> bool for this account is credit or debit

balance -> final balance after this transaction

enter image description here

Upvotes: 2

Views: 1068

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138834

If you want to add "transactions" to an existing account, you have two options. Since a transaction is an object with different properties (amount, date, details, is_credit, balance), you can add such an object into an array of "transactions", that can be a property within your account document. Your schema should look like this:

Firstore-root
  |
  --- accounts (collection)
        |
        --- pTSc...0Onp
              |
              --- address: "1200"
              |
              --- //Other details
              |
              --- transactions (array)
                    |
                    --- 0
                    |   |
                    |   --- amount: 300
                    |   |
                    |   --- date: February 28, 2020 at 3:37:59 PM UTC+3
                    |   |
                    |   --- details: "Transaction details"
                    |   |
                    |   --- is_credit: true
                    |   |
                    |   --- balance: 1200
                    |
                    --- 1
                        |
                        --- amount: 100
                        |
                        --- date: February 28, 2020 at 5:21:22 PM UTC+3
                        |
                        --- details: "Other transaction details"
                        |
                        --- is_credit: false
                        |
                        --- balance: 3600

This solution will work only as long as you are 100% sure that the size of the document will stay within the 1Mib limitation:

Maximum size for a document: 1 MiB (1,048,576 bytes)

If that's not the case, then you should consider adding those Transaction objects within a subcollection that can exist within the Account document. In that case, there is no limitation about the number of documents that can be added to that subcollection.

Upvotes: 4

Related Questions