0

I want to return an array of parent keys that contain the given child key.

Here is my database (member user IDs with the IDs of every group they are in):

database.

For example:

  • If I provide -Lu3Zs4FCW6F4IcMSU8K it should return the two parent keys, SnGXDFilErWEqFxPgWY5bIIAnPA3 and t1S9N9owgKRGqBaNxs02rru8GpD3.
  • If I provide -Lu3gCYh5QUplnwLdOFA it should only return t1S9N9owgKRGqBaNxs02rru8GpD3

The child values (0 or 1) are not known.

Here is what I tried so far:

var members = [];

return await firebase.database().ref('members').orderByChild(groupId).once('value', snap => {
    snap.forEach(data => {
        members.push(data.key);
    });
}).then(() => {
    return members;
});

But this code returns both member keys no matter what child key I provide. Any help would be appreciated.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Robert Berge
  • 365
  • 3
  • 12

1 Answers1

1

Your current data structure allows you to efficiently find the groups for a given member. It does however not allow you to efficiently find the members for a given group.

To allow the latter use-case, consider adding an additional data structure that is pretty much the inverse of what you have now:

"groups": {
  "-Lu3Zs4FCW6F4IcMSU8K": {
    "SnGXDFilErWEqFxPgWY5bIIAnPA3": true,
    "t1S9N9owgKRGqBaNxs02rru8GpD3": true
  },
  "-Lu3gCYh5QUplnwLdOFA": {
    "t1S9N9owgKRGqBaNxs02rru8GpD3": true
  }
}

Now you can look up the members of a group in the same way you look up the groups of a member.

Also see my answer here:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807