Search code examples
firebasegoogle-cloud-firestorefirebase-security

How to validate an array of data in Firebase Firestore?


I have a profile collection in Firebase:

{
  "name": "Lars",
  "age": 53,
  "posts": [
    {
      "title": "My first post!",
      "body": "This is my first post!"
    },
    {
      "title": "My second post!",
      "body": "This is my second post!"
    }
  ]
}

The user will update his posts from the frontend. How can I ensure he is only putting in posts which title and body field to this document? I don't want to create a collection with posts below.

Is this possible with firestore rules or I am forced to create a collection?


Solution

  • Since you can't iterate anything in rules, you can't write rules that check array contents.

    You will have to create a new collection so that you can restrict access to named fields. This is always the right way to go for lists of data that have no strict upper bound in size, anyway. If you are packing things into an array to try to save on document reads, that's also not usually the right way to go. Your data model should reflect the expected access patterns for your data, which in your case, appears to involve a lot of per-item access - that's much easier done when each item is a document.