Home > Blockchain >  Firestore data structure for two use cases
Firestore data structure for two use cases

Time:03-29

I would appreciate some guidance on how to structure data stored within an app. While there are some reasons for the first way, I'm concerned it wouldn't be able to operate efficiently for the second case.

Simplified, the app would contain a list of Places by State. The main use case would be viewing Places within a selected State. The second use case would be that individual users could save specific Places they liked into their profile and view them all at once (showing all state Places in one list).

Option 1- Places saved in one "places" collection, which has a field of "state."

Main use: To show these places by state, the app would query where the "state" field matches the state.

Secondary use: When a user saved the place, the app would save the docID for each place into the user's profile, each of which would need to be retrieved to show the list of places.

Option 2- Have one collection per state.

Main use: To show these places by state, the app would pull all documents within the query and list them out.

Secondary use: When a user saved the place to the user's profile, the app would save the docID for each place into the user's profile, distributed across the different collections, each of which would need to be retrieved to show the list of places.

Goals:

  1. Use the same place document to appear in both the State lists and the user's profile.
  2. Minimize the number of calls/slowness as much as possible in the Secondary use case.

I have been reviewing Firestore data storage guidelines, but I would appreciate any thoughts from experienced developers regarding this data structure.

CodePudding user response:

There is no "perfect", "the best" or "the correct" solution for structuring a Firestore database. We are usually structuring the database according to the queries that we intend to perform.

Regarding storing all the places in a single collection vs. having one collection per state, please note that there is no difference in terms of speed or costs. You'll always have to pay a number of reads that is equal to the number of documents your query returns. However, if you need to display in your app, for example, all places of all states, then having a collection for each state, will require a separate query for each state.

Furthermore, regarding saving a list of places in a user's profile vs. storing only the IDs, it's a matter of calculation. You should measure how often the data within the places are changed. Remember that if a place is changed, then you should update that data in all places it exists. So if it's not so often then you can save the entire place object, otherwise, save only the ID.

  • Related