angular firestore如何检索多对多关系数据

问题描述 投票:0回答:1

我来自RDMS背景。我很难通过关联集合获取关系数据,这是我得到的集合...

users collection
- user_1
  - name: abc
  - email: [email protected]
- user_2
  - name: efg
  - email: [email protected]

groups collection
- group_tech
  - name: tech
- group_finance
  - name: finance

groupUsers collection
- groupUserID
  - groupID: group_tech
  - userID: user_1

我想列出技术组中的用户,基本上我可以像这样查询

this.groupUsersCol = this.afs.collection('groupUsers');

this.groupUsersCol.ref.where('groupID', '==', this.params.gid)
  .onSnapshot(function(querySnapshot) {
      var employees = [];
      querySnapshot.forEach(function(doc) {

        // here i only get the user id, how i get the user doc? 
        // Also, i cannot direct call this.afs.doc(...)
        console.log("user", doc.data())
      });
  });

还有另一种方法可以解决我以这种方式对数据进行建模的问题。

users collection
- user_1
  - name: abc
  - email: [email protected]
  - groups: {
      group_tech: true
    }
- user_2
  - name: efg
  - email: [email protected]
  - groups: []

groups collection
- group_tech
  - name: tech
  - users: {
      user_1: true
    }
- group_finance
  - name: finance

以这种方式存储数据的好处是检索数据非常方便。喜欢...

如果你想获得组中的所有用户,你可以查询

this.afs.collection('users').ref.where('groups.'+group_id, '==', true)

对用户来说同样的事情,获得​​用户的群体,绝对容易。但是从组中删除用户时存在缺点。你需要从2表中删除。

请指教!分享您的经验和实践方法,这将是一件好事,欢迎并非常感谢您!

javascript firebase google-cloud-firestore angularfire2
1个回答
0
投票

我建议采用第二种方式,正如您所提到的那样,它可以更好地查询并简化您的安全规则。请注意复合索引有20k的限制,所以如果您的用户在数千个组中,请不要这样做。

为了解决这个缺点,不是处理“删除”客户端,而是使用云功能在服务器端执行。只需使用Cloud Functions侦听器监视用户和组,查找已更改的字段,如果现在有任何关系,false将删除关系的两侧。

© www.soinside.com 2019 - 2024. All rights reserved.