How can I enforce database schema in Firestore?

Viewed 2777

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?

3 Answers

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.

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]

Related