1

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95

1 Answers1

1

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:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • yes that'a a better structure for finding the event_user relation and the user_event relation, but i'll need to read the database more than one time. Is there any way to read all information at once? thanks for your help. – Roberto Salazar Dec 20 '17 at 18:37
  • You'll need to read from each top-level node separately. While it's a bit messy in code, it's not as slow as you may expect since Firebase pipelines the requests. 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 Dec 20 '17 at 18:58
  • thanks man, i'll read the NoSQL data modeling. I'm new at nosql databases and sometimes it is a little messy. You saved me thanks. – Roberto Salazar Dec 20 '17 at 19:09