【问题标题】:Firestore data modeling to get x unknown amount of documents that the user has permission to access from collectionFirestore 数据建模以获取用户有权从集合中访问的 x 个未知数量的文档
【发布时间】:2019-11-22 14:38:28
【问题描述】:

我想要的是能够发送一个查询,返回用户所在的所有团队,所以 f.ex。 uid1 将返回 team1,但不返回其他团队。我当前的模型不起作用,因为我只是遇到权限问题,因为用户无权阅读 Teams 集合中的所有文档。

Teams 集合可以包含多个团队,并且用户可以是多个团队的一部分。

这就是我当前的 Firestore 的组织方式:

Users:
    uid1
        firstname: xxxx
        lastname: yyyy
Teams:
     team1
         subCollection1
             ...
         subCollection2
             ...
         members
             uid1
             ...
         roles
             uid1
                 role: dev
    team2
        ...

我只能想到两种解决方案,但似乎都不是很好。

  1. 在 Users 集合中的每个用户下都有一个列表/子集合,其中包含用户所在的所有团队。
  2. 在包含团队成员所有 uid 的 Teams 集合内的每个文档中都有一个数组类型的字段。 (然后使用 .where("members", "array-contains", uid))

组织数据以实现我想要的功能的最佳方式是什么?

【问题讨论】:

  • 不要描述你的数据库的样子,而是添加它的截图。

标签: firebase google-cloud-firestore


【解决方案1】:

您可以在“用户”下创建一个子集合并执行 collectionGroup 查询以获取该团队中的所有用户,或执行常规查询以获取用户所在的所有团队。您只需将 teamID 存储在子集合中,如果需要,还可以存储一些其他静态信息。

Users:
    uid1
        firstname: xxxx
        lastname: yyyy
        teams (collection)
             teamID (document)
             teamID (document)
    uid2
        firstname: xxxx
        lastname: yyyy
        teams (collection)
             teamID (document)
Teams:
     team1
         subCollection1
             ...
         subCollection2
             ...
         roles
             uid1
                 role: dev
      team2
          ...

现在也无需在Teams 下存储members,因为您可以通过Users 集合运行所有查询,并且一旦您拥有teamID,您就可以用它做任何您想做的事情。

您还必须更改 collectionGroup 查询的权限才能使其正常工作。

如:

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {

    match /{path=**}/teams/{teamID} {

      allow read: if request.auth.uid != null;

    }

    match /users/{userID}/teams/{teamID} {

      allow write: if request.auth.uid == resource.data.author;

    }
  }
}

【讨论】:

  • 谢谢,但我将如何编写安全规则,以便只有团队成员才能读取团队成员的身份。我试过match /{path=**}/teams/{team} { allow read: if exists(/databases/$(database)/documents/users/$(request.auth.uid)/teams/$(team)); },但它似乎不起作用,因为我得到了权限被拒绝的错误。
猜你喜欢
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
  • 2020-08-15
  • 2018-07-01
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多