0

I have a firebase database like this structure:

-groups
--{group1id}
---groupname: 'group1'
---grouptype: 'sometype'
---groupmembers
----{uid1}:true
----{uid2}:true
--{group2id}
---groupname: 'group2'
---grouptype: 'someothertype'
---groupmembers
----{uid1}:true
----{uid3}:true
----{uid4}:true

Now, I am trying to pull groups of authenticated user. For example for uid1, it should return me group1id and group2id, and for example uid3 it should just return group2id.

I tried to do that with this code:

        database().ref('groups/').orderByChild('groupMembers/' + auth().currentUser.uid).equalTo('true').on('value' , function(snapshot) {


        console.log('GROUPS SNAPSHOT >> ' + JSON.stringify(snapshot))

    })

but this returns null. if I remove "equalTo" and go it returns all childs under 'groups'.

Do you know any solution or better database structure suggestion for this situation ?

ugrdursun
  • 351
  • 1
  • 4
  • 19

1 Answers1

1

Your current structure makes it easy to retrieve the users for a group. It does not however make it easy to retrieve the groups for a user.

To also allow easy reading of the groups for a user, you'll want to add an additional data structure:

userGroups: {
  uid1: {
    group1id: true,
    group2id: true
  },
  uid2: {
    group1id: true,
    group2id: true
  },
  uid3: {
    group2id: true
  },
  uid3: {
    group2id: true
  }
}

Now of course you'll need to update both /userGroups and /groups when you add a user to (or remove them from) a group. This is quite common when modeling data in NoSQL databases: you may have to modify your data structure for the use-cases that your app supports.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for your suggestion it makes sense, but with that way like you said, i need to update more things on database and while pulling it need to use additional codes and it will be slower. If i not use "groupMembers", (just put the uid1:true under the {groupid} ; with orderByChild(uid) it would work. So problem here is putting them under "groupMembers" isn't it ? I wondered if i can sort that out – ugrdursun Mar 24 '20 at 10:27
  • 1
    "while pulling it need to use additional codes and it will be slower" That's an assumption that you'll want to test. Firebase pipelines requests and is typically a lot faster than devs initially assume. See https://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Mar 24 '20 at 13:46