如何仅允许公开访问firestore文档的特定字段

Muh*_*qib 6 firebase firebase-realtime-database google-cloud-firestore

假设我在firestore数据库中有这个结构:

collection[
  document: {
    x: 'x',
    y: 'y'
  }
]
Run Code Online (Sandbox Code Playgroud)

我有这个firebase规则:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是这个规则暴露了document上面的整体collection,我想要做的只是暴露x场,是否可能?谢谢

Tod*_*man 12

你不能.安全规则仅适用于文档级别,因此您无法限制对特定字段的读取权限.

如果您想要执行类似于您建议的操作,则可能需要重新构建数据,以便将非公开数据放在单独的文档中.您很可能希望通过将私有数据放入子集合中来实现此目的.所以你最终会得到这样的东西......

collection: [
  document: {
    y: 'y'
    private-collection: [
      document: {
        x: 'x'
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

然后你会设置你的安全规则,如:

service cloud.firestore {
  match /databases/{database}/documents {
    match /collection/{document} {
      allow read: if true;
      match /private-collection/{otherdoc} {
        allow read: if someOtherRuleThatYouAddHere();
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 子集合是一个很好的解决方法。firebase 文档中对此进行了解释 - https://firebase.google.com/docs/firestore/security/rules-struct#hierarchical_data (2认同)