Search code examples
google-cloud-firestorefirebase-security

Firestore security rule for array of maps


I'm writing to Firestore and creating a doc that has a field that is an Array of quite simple maps e.g.

docField : [
 {
   name: 'Bob',
   age: 42,
   type: 'default'
 }, ...
]

I want to write a security rule to validate the map fields and their request contents. I know I can validate fields with something like,

allow write:
   if request.resource.data.name is string
   && ...

But how do I apply this to all N of the items of an Array field? I have seen some people just brute force each item in the list when the length is known but I don't know how many items I'll have to deal with - not hundreds but likely tens.

I can only think of putting each map into its own document in a subcollection and writing a rule for that but that seems like a lot of writes to perform for data that doesn't require it.

Any tips?


Solution

  • I have seen some people just brute force each item in the list when the length is known but I don't know how many items I'll have to deal with

    That's because this is really the only possible solution with security rules. There are no loops or maps available to use for iteration. The security rules system is designed to be small, fast, and deterministic in order to minimize performance issues (since they potentially intercept every single matching read or write). Loops over collections of unknown size work against those goals.

    I can only think of putting each map into its own document in a subcollection and writing a rule for that but that seems like a lot of writes to perform for data that doesn't require it.

    This is likely your only viable solution given the above constraints.