Roberto Salazar
Roberto Salazar

Reputation: 33

Firebase query of child key

I have the next structure in my firebase database:

{
    events: {
       event_1:{
           startdate: 120934210,
           enddate: 120934211,
           members: {
               uid_1: true,
               uid_2: true,
               ...
           }
       },
       event_2:{
           startdate: 120934210,
           enddate: 120934211,
           members: {
               uid_2: true,
               uid_3: true,
               ...
           }
       },
       ...
    }
}

I have a node event and every child is an event, each event have a list of members. The question is, how can I do a query for all events of a certain member? For example, all events with member uid_2. I'm using angularfire2 and angular 4. I'm trying to do something like that:

db.list('events/',ref => ref.orderByChild('members').equalTo(uid))

please help me.

Upvotes: 1

Views: 893

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Your current data structure allows you to easily find the members of a specific event. If does not allow you to easily determine the events for a specific user. To allow that, you should add an inverted data structure.

It is also recommended to not nest different entity types, but instead store them in top-level nodes.

For your data this leads to four likely top-level nodes:

users: {
  $uid: { ... }
},
events: }
  $eventid: { ... }
},
event_users: {
  $event_id: {
    $uid: true
  }
},
user_events: {
  $uid: {
    $event_id: true
  }
}

Now you can easily read (without querying) the members for an event, and the events for a user.

I also recommend you check out:

Upvotes: 1

Related Questions