Trying to model a SQL table structure in a NoSQL database like Firebase is a recipe for pain. Stop thinking about SQL concepts like inner joins and group by clauses.
Instead embrace the nature of the platform you are using. For example: do you need to usually show the list of transactions for an account? If so, why not model that in your JSON tree:
accountTransactions
accountId1
transaction1: {
type: "entertainment"
...
}
transaction2: {
type: "food"
...
}
accountId2
transaction3: {
type: "food"
...
}
transaction4: {
type: "food"
...
}
Now if you want the list of transactions for account 1, instead of needing a query, you can directly them from /accountTransactions/accountId1
.
If you also want other lists of transactions, you may need to duplicate some of the data in your tree. For example, if you want to show a list of all food transactions, you could add this to the database:
transactionPathsByType
food
transaction2: "/accountTransactions/accountId1/transaction2"
transaction3: "/accountTransactions/accountId2/transaction3"
transaction4: "/accountTransactions/accountId2/transaction4"
There are many ways to model this last relationship. For example, you could also keep the list of transactions as a single flat list:
accountTransactions
transaction1: {
account: "accountId1"
type: "entertainment"
...
}
transaction2: {
account: "accountId2"
type: "food"
...
}
transaction3: {
account: "accountId2"
type: "food"
...
}
transaction4: {
account: "accountId2"
type: "food"
...
}
Which would simplify the mapping from transaction type to transactions to:
transactionIdsByType
food
transaction2: true
transaction3: true
transaction4: true
We're just using true
as a dummy value here, since all the information needed to look up each transaction is already present in the key.
If you with the straight list of transactions also want a quick way to look up the transaction IDs for an account, you could add an index that maps the account ID to the corresponding transaction IDs:
transactionIDsByAccount
accountId1
transaction1: true
transaction2: true
accountId2
transaction3: true
transaction4: true
There are as many possible models as there are app ideas out there. More probably. For a good introduction article, I recommend reading NoSQL data modeling. Definitely also watch Firebase for SQL developers on youtube.