对象数据类型的 Firestore 规则

Firestore rules on object data type

数据库有一个集合 "Collection",集合中的每个文档都有一个对象 "members",其中包含 "uid" 可以访问该文档的用户。

Collection--->document-->members = {"BZntnJO2PVS8OZ9wctwHiyxBytc2": true} 

我尝试了很多不同类型的规则,但 none 这些规则似乎有效

service cloud.firestore {
  match /databases/{database}/documents {
  match /collection/{documentId} {
         allow read: ****
 }
}

1)

allow read: if get(/databases/$(database)/documents/collection/$(documentId)).members[request.auth.uid] != null

2)

allow read: if resource.data.members[request.auth.uid] != null

3)

allow read: resource.members[request.auth.uid] != null

4)

allow read: if request.resource.data.members[request.auth.uid] != null

5)

allow read: request.resource.members[request.auth.uid] != null

会不会是 Firestore 的错误?

您需要访问 data 属性 才能访问任何用户创建的属性,因此规则 1、3 和 5 将不起作用。

request.resource 通常指的是您发送到数据库的数据,通常是在写操作的情况下,所以规则 #4 不起作用,因为 request.resource.data 会在读取的情况下可能为空。

规则 #2 看起来确实正确,但请记住,这仅适用于获取单个文档的情况。查询有点棘手。

具体来说,如果您要运行进行一般的 "Get every document in my collection" 查询,Cloud Firestore 没有时间搜索数据库中的每条记录以确保您的用户有访问,因此它将拒绝此查询。相反,您需要 运行 一个查询,其中 Cloud Firestore 可以 "prove" 您检索的所有文档都是有效的。例如,在您的情况下,您需要确保您的查询类似于 "Get every document in my collection where members.(userID) != null"。然后,Cloud Firestore 规则可以将您的查询与其规则进行比较,并且您会感到满意,因为您只会获得您有权访问的文档。