Firebase data calculations on a nested structure

kirtan403 Source

I have recently come across Firebase at 2016 I/O and decided to move to firebase because having issues with the current syncing database. I used to calculate amounts with map/reduce with my previous NoSQL database. But, no map/reduce in firebase. So, what is the effcient way of calculating the amounts for the firebase from the structure explained below, or is there any better way to structure for calculations?

Structure: Users can add expense details for the events they are participating. While expense details can contain of multiple people and for multiple people.

So for example, Person A is paying 100, and B is paying 200 for them distributed equally.

In firebase, it would something like this:

"expenses" : {
    "-randomId1" : {
        "event" : "eventId",
        "desc" : "event tickets",
        "who_paid" : {
            "uid-for-A" : {
                "amount" : 100
            },
            "uid-for-B" : {
                "amount" : 200
            }
        },
        "paid_for" : {
            "uid-for-A" : {
                "amount" : 150
            },
            "uid-for-B" : {
                "amount" : 150
            }
        }
    },
    ...
    // Another event expenses .. 
    ...
}

I can also store aggregately for per user at a node directly under expenseId like:

"expenses" : {
    "-randomId1" : {
        "event" : "eventId",
        "desc" : "event tickets",
        "aggregation" : {
            "uid-for-A" : -50, // 100 - 150
            "uid-for-B" : 50   // 200 - 150
        }
        "who_paid" : {
            "uid-for-A" : {
                "amount" : 100
            },
            "uid-for-B" : {
                "amount" : 200
            }
        },
        "paid_for" : {
            "uid-for-A" : {
                "amount" : 150
            },
            "uid-for-B" : {
                "amount" : 150
            }
        }
    },
    ...
    // Another event expenses .. 
    ...
}

How to calculate total expenses at the end of the event, for each user?

What if there are more than 100s of expenses for longer events? How can I do this in firebase?

databasedatabase-designfirebasefirebase-realtime-database

Answers

comments powered by Disqus