简体   繁体   中英

Query for multiple records in firebase

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 eg 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 ie 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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM