0

I have a firebase datbase set up as follows: https://ibb.co/h8nQPZY

I want to retrieve a list of uids of all the groups that the given user uid appears in. For example, if I pass 'SnGXDFilErWEqFxPgWY5bIIAnPA3', it should return an array containing '-LstfBZj3hKDxpf8QxpT', as well as any other groups that user is in.

Here is what I have right now, although I've tried a few different things and it seems illogical:

async listGroups(userUid) {
    let groups = [];

    await firebase.database().ref('groups').orderByChild('members').equalTo(userUid).on('value', snap => {
      snap.forEach(data => {
        groups.push(data.key);
      });
    });

    return groups;
  }

Any help would be appreciated.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Robert Berge
  • 365
  • 3
  • 12
  • You've included a link to picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export JSON link in the overflow menu (⠇) of [your Firebase Database console](https://console.firebase.google.com/project/_/database/data/). Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do. – Frank van Puffelen Nov 05 '19 at 05:31
  • The data structure you have makes it easy to find the users for a given group. It does not make it easy however to find the groups for a specific user. For that you'll want to add an additional data structure `/users/$uid/groups/$groupid`, somewhat inverted of what you now have. With this inverted index you can then implement your use-case. See my longer explanation here: https://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Nov 05 '19 at 05:34

0 Answers0