2

I have a database in Firebase that has the following structure:

{
   groups: {
      "$groupId1": {
         name: "My group",
         members: {
           "$userId1": true,
           "$userId2": true
         },
         creator_id: $userId1
      }
   },
   users: {
      "$userId1": {
          groups: {
            '$groupId1': true
          }
      },
      "$userId2": {
          groups: {
            '$groupId2': true
          }
      }
   }
}

I am also using AngularFire.

If I want to find all of the groups that a given user has created, I can use a query like this:

// rootRef is my Firebase root ref
var groupsForCreatorRef = rootRef.child("groups").orderByChild("creator_id").equalTo(userId);

I can then wrap this in $firebaseArray, like so:

$firebaseArray(groupsForCreatorRef);

I'd like to do something very similar, but for all of the groups that a given user is a member of, not just the groups that the user has created. Can I do this, given my data structure? That is, I'd like to be able to do something like this:

$firebaseArray(rootRef.child("groups").orderByChild("members").contains(userId));

But there is no such ".contains" query.

Alternatively, I could look up the user's group ids, like so:

rootRef.child("users").orderByKey().equalTo(userId).child("groups");

And then I can look up the groups, using these group ids. But is there a way I can do this all at once, instead of looking up each group with its ID, one by one? I ask because I want to be able to make use of the $firebaseArray, as I've shown above, and I'm not sure I can use $firebaseArray if I have to retrieve each group one by one.

jyli7
  • 2,731
  • 6
  • 23
  • 31
  • Looking up the groups one-by-one is not significantly slower than getting them all in one go. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Oct 20 '16 at 16:59
  • Joining data in `$firebaseArray` is one way of doing this. See this answer for a good example: http://stackoverflow.com/questions/30299972/joining-data-between-paths-based-on-id-using-angularfire – Frank van Puffelen Oct 20 '16 at 17:00

0 Answers0