How can I enforce database schema in Firestore?
Asked Answered
R

4

8

I'd like to enforce a database schema in Firestore, a noSQL style database that does not require scheme by default.

So far, I've looked into using the Firebase Rules system as a possible avenue for schema enforcement: https://firebase.google.com/docs/firestore/security/rules-structure

I would like to:

  1. Ensure that certain fields have the proper data type (String, Number, bool)
  2. Ensure that certain fields exist (ex: firstName and lastName on a User class)
  3. Ensure that fields are set to 'undefined' if not needed. (This one I'm not sure about - do I need to do this?)

Has anyone found a good way to enforce schema from the server side?

Retention answered 17/12, 2018 at 16:43 Comment(0)
M
1

Firestore is not a relational database so the concept of a schema is not applicable [source Cloud Firestore Data model]. Data types in Firestore are enforced by firestore.rules security rules.

In a relational database, the schema defines the tables, fields, relationships, views, indexes, packages, procedures, functions, queues, triggers, types, sequences, materialized views, synonyms, database links, directories, XML schemas, and other elements.

[Wikipedia]

Millinery answered 17/12, 2018 at 17:2 Comment(0)
I
3

It sounds like you already found your answer - security rules. They can check to make sure everything is set the way you expect. You should know that this works for all access through the client SDKs, but does not when using the Admin SDK on your backend, if any.

You can also use Cloud Functions to perform more checks after the data has been added, then undo the operation if there's still something wrong.

Inclinable answered 17/12, 2018 at 16:47 Comment(0)
M
1

Firestore is not a relational database so the concept of a schema is not applicable [source Cloud Firestore Data model]. Data types in Firestore are enforced by firestore.rules security rules.

In a relational database, the schema defines the tables, fields, relationships, views, indexes, packages, procedures, functions, queues, triggers, types, sequences, materialized views, synonyms, database links, directories, XML schemas, and other elements.

[Wikipedia]

Millinery answered 17/12, 2018 at 17:2 Comment(0)
F
0

Shall use schema description and validation library such as Joi - https://github.com/hapijs/joi

Fraise answered 9/3, 2020 at 8:35 Comment(0)
I
0

A bit late to the party but if anyone is still looking to enforce a schema in Firebase then take a look at Fireschema. A more radical option is to look at Supabase.

Id answered 14/7, 2023 at 16:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.