Firestore 规则 |使用 resource.data 获取 collection 时权限不足

Firestore Rules | Insufficient permission when using resource.data on getting collection

我的 Firestore 规则

match /fruits/{fruit} {
  allow read: if request.auth.uid == resource.data.user;
}

现在读取单个文件,没有问题

db.collection("fruits").doc('apple').get()

但是当我尝试获取 collection 时,它给了我 permission-denied

db.collection("fruits").get()

当您尝试查询 'fruits' 集合中的所有文档时,安全规则会检查这些文档中的 user 字段是否等于用户请求数据的 UID。如果任何一个文件不符合条件,它会抛出一个权限错误。相反,您应该在查询中添加一个 where() 子句,如下所示:

db.collection("fruits").where("user", ==, currentUserUID).get()

此查询将查找用户字段与用户 UID 匹配的文档,并且所有匹配的文档都将通过安全规则 if request.auth.uid == resource.data.user;。安全规则不是过滤器,这意味着它们不会根据规则从集合中过滤掉文档。您必须以这种方式编写查询。