How to design a Cloud Firestore database schema

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.


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.