17

Suppose I have this structure in a firestore database:

collection[
  document: {
    x: 'x',
    y: 'y'
  }
]

and I have this firebase rule in place:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
    }
  }
}

But this rule exposes the whole document in the above collection, What I want to do is to expose only x field, is it possible? Thanks

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Muhammad Saqib
  • 1,037
  • 3
  • 10
  • 16
  • 1
    Possible duplicate of [Firestore Rules to restrict write access to a specific field in a document](https://stackoverflow.com/questions/48314542/firestore-rules-to-restrict-write-access-to-a-specific-field-in-a-document) – Herohtar Aug 16 '18 at 04:45

2 Answers2

28

You can't. Security rules only work on a document-level basis, so you can't restrict read access to specific fields.

If you want to do something like you're suggesting, you'll probably need to restructure your data so that your non-public data is in a separate document. Most likely you'll want to do this by putting your private data in a subcollection. So you might end up with something like this...

collection: [
  document: {
    y: 'y'
    private-collection: [
      document: {
        x: 'x'
      }
    ]
  }
]

And then you'd set up your security rules like:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
      match /private-collection/{otherdoc} {
        allow read: if someOtherRuleThatYouAddHere();
      }
    }
  }
}
Todd Kerpelman
  • 16,875
  • 4
  • 42
  • 40
  • is private-collection is a subcollection name ? and what is otherdoc refer to ? – Aman Aggarwal Feb 15 '18 at 05:09
  • 2
    sub-collections is a nice workaround. it is explained in the firebase docs - https://firebase.google.com/docs/firestore/security/rules-structure#hierarchical_data – Yinon Apr 14 '19 at 15:20
2

YOU CAN!

not do this for reading, but for updating. This is not what was asked for, but it's probably what many people came here for - including myself.

allow update: request.resource.data.diff(resource.data).affectedKeys().hasOnly(['MyField']);

Docs

mathematics-and-caffeine
  • 1,664
  • 2
  • 15
  • 19