2

Firebase orderByChild() works well when child properties have names, so that with data like this:

groups
    <groupID>
        groupStatus: "Active"

is is easy to get the groupIDs of the groups with "Active" status by this:

var ref = "http://myFirebase.firebaseio.com/groups";
ref.orderByChild("groupStatus").equalTo("Active").on("child_added", function(snapshot) {
    console.log(snapshot.key());
});

But I have firebase data of groups and the members of those groups in the following form:

groups
    group123
        member404: true
        member503: true
        ...
    group124
        member503: true
        member221: true
        ...

I need to generate a list of all the memberIDs who are "friends" of a particular member, defined as being in at least one group in common with them. For member 503, you would think this would be a orderByChild() opportunity. But since the memberIDs are keys nested under the groups, what would the syntax be?

Something like:

ref.orderByChild(???).equalTo("member503")

Of course, I could get all the members of all the groups into an array locally, but surely there is a way to get firebase to do this for me?

David Gilmour
  • 23
  • 1
  • 3

1 Answers1

6

You're mixing up child keys and values here. The solution:

ref.child('groups').orderByChild('member404').equalTo(true)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Yes, `membersRef.orderByChild(uid).equalTo(true)` works for the query, but now my problem is how to create an index to make it perform. Firebase complains "Consider adding ".indexOn": "41ab3832-6a90-4141-bdf5-92c5cac0f99c" which is a specific member ID. Obviously, that's not practical. And it's not possible to use $location variable in index specification. Anyone know how to index this correctly? – David Gilmour Nov 06 '15 at 12:43
  • Yup. You'd do that by creating your own so-called *reverse index*. In your list of users, also keep track of the groups they're a member of. That way you can do a direct look-up of "groups for user" and of "users for group". In a NoSQL world, direct look-up will always trump querying for the same data. Have a read here: http://stackoverflow.com/questions/16638660/firebase-data-structure-and-url/16651115#16651115 – Frank van Puffelen Nov 06 '15 at 15:18