Query for multiple records in firebase

804 views Asked by At

I'm implementing an orbit.js adapter for firebase, orbit-firebase.

I'm looking for an efficient way to query for multiple records so that I can resolve relationships between objects e.g. course.participants

{
  course: {
    'c1': {
      participants: ['p1', 'p2']
    }
  },
  participant: {
    'p1': {
      name: "Jim"
    },
    'p2': {
      name: "Mark"
    }
  }
}

Given I have the ids 'p1' and 'p2' what's an efficient way to query for both of them?

I can't use a query because I'm using security rules with the participants i.e. the user that's trying to resolve course.participants doesn't have access to all of the participants (bear in mind this is a contrived example).

1

There are 1 answers

5
Kato On

I'd recommend that you move away from arrays in your JSON structures. These are nothing but pain in real-time, distributed data and don't work particularly well with security rules and situations like this.

Given this structure:

course: {
  'c1': {
    participants: {
       'p1': true, 'p2': true
    }
  }
}

I could join these fairly easily. You can get a normalized ref that behaves just like a Firebase ref by using Firebase.util's NormalizedCollection:

var ref = new Firebase(...);
var coll = new Firebase.util.NormalizedCollection(
   ref.child('course/c1/participants'),
   ref.child('participant')
).select('participant.name').ref();

coll.on('child_added', function(snap) {
   console.log('participant ' + snap.key(), snap.val());
});

Note that this data structure (sans the array) will also make it simpler to enforce read rules on participant data and the like by allowing you to directly reference the user ids under $courseid/participants/, since they are now keys that can match a $ variable.