Home > Net >  Storing data in Firebase for optimal reading and use for statistics
Storing data in Firebase for optimal reading and use for statistics

Time:11-06

I'm new to storing data in Firebase. I'm creating my very first app and I want to create the data correctly from the beginning.

What I want to do is that when the customer choose a voucher (for use when purchase meals) I also want them to choose what type of meal that they are going to eat and store statistics on that. The type of meal could be, vegetarian, soup, salad, fish, meat.

So my first question is, is it best to store the type of meals under document for each type or use a map or perhaps an array.

Later on, when they choose the type of meal, I have a statistics collection, there I want to store statistics on how many meals of soup, etc they have been eating during the week and month.

Any hints etc are greatly appreciated

CodePudding user response:

Is it best to store the type of meals under document for each type or use a map or perhaps an array.

If a meal can be labeled with a single type, then you can store the type like this:

Firestore-root
  |
  --- meals (collection)
       |
       --- $mealId (document)
            |
            --- type: "soup"

If a meal can be labeled using multiple types, then you can either use an array:

Firestore-root
  |
  --- meals (collection)
       |
       --- $mealId (document)
            |
            --- type: ["soup", "salad"]

Or a map:

Firestore-root
  |
  --- meals (collection)
       |
       --- $mealId (document)
            |
            --- type
                 |
                 --- soup: true
                 |
                 --- salad: true

When you use a map, you can easily create multiple whereEqualTo() function calls. So you have to choose which one of the above solutions fits best your app's use case.

Later on when they choose the type of meal, I have a statistics collection, under there I want to store statistics on how many meals of soup, etc they have been eating during the week and month.

For that I recommend you use a schema like this:

Firestore-root
  |
  --- statistics (collection)
       |
       --- $uid (document)
            |
            --- soup: 2
            |
            --- salad: 7

In this way, you can keep a counter for each user, of how many meals you provided. If you need a more complex schema, you can store those meals as documents inside a collection and add each meal as a document containing a Timestamp. In this way, you'll be able to query on Timestamp ranges.

  • Related