How to design a Cloud Firestore database schema

14,973

Solution 1

For Question 1 there's a solution in the firestore docs: https://cloud.google.com/firestore/docs/solutions/arrays

instead of using an array you use a map of values and set them to 'true' which allows you to query for them, like so:

teachers: {
        "teacherid1": true,
        "teacherid2": true,
        "teacherid3": true
    }

And for Question 2, you just need to save the teacher-ids because if you have those you can easily query for the corresponding data.

Solution 2

In general: keep the data store as shallow as possible, i.e., avoid subcollections and nesting.

Data can be related one-to-one, one-to-many, or many-to-many. Firestore is an automatically indexed realtime datastore. Firestore is often subscribed to rather than just a one time query/response (the realtime nature of the system).

Regarding the Firestore data model, always consider How will I query this data store?. Use subcollections, arrays, and maps sparingly (rarely) and only if you must (and you most likely don't need to). Use auto-id's vs human readable id's, e.g. use 000kztLDGafF4uKb8Cal rather than banana for document ID's.

As app functionality increases, server-side scripting with Cloud Functions for Firebase and/or the Admin SDK becomes an invaluable tool for managing (creating and indexing) many-to-many data relationships. For example, full-text search is not supported in Firestore. This boils down to what seems like a barrier to implementing robust search functionality on your app.

In conclusion, try and avoid subcollections, nesting, arrays, and maps. Follow the keep it simple stupid, KISS, principle. Once your app scales up and/or requires more functionality, server-side scripting can be utilized to to keep your app responsive (fast) while offering robust features.

Share:
14,973
Hans Anker
Author by

Hans Anker

Updated on July 07, 2022

Comments

  • Hans Anker
    Hans Anker almost 2 years

    Migrating from realtime database to cloud firestore needs a total redesign of the database. For this I created an example with some main design decisions. See picture and the database design in the spreadsheet below. My two questions are:

    1 - when I have a one to many relation is it also an option to store information as an array within the document? See line 8 in database design.

    2 - Should I include only a reference, or duplicate all information in the one to many relation. See line 38 in the database model.

    enter image description here

    https://docs.google.com/spreadsheets/d/13KtzSwR67-6TQ3V9X73HGsI2EQDG9FA8WMN9CCHKq48/edit?usp=sharing