1

I have an array of objects related to users and want to get all objects related to one user. I can't save the userid as a parent node but as a child so that I want to use the equalTo method.

ref.orderByChild("userid").equalTo(uid).on("child_added", function(snapshot) {
  console.log(snapshot.val());
});

Does this first query all objects (slow) and then select only the required ones or does firebase optimize the query itself on the server? I come from SQL and I am a bit unsure how to handle where queries in firebase.

Edit: there are also security issues. A user could receive all objects by hacking the js code? I hope the security rules should solve this?

Example JSON:

{
   Objectkey1: { userid: 'uid', ... },
   Objectkey2: { userid: 'uid', ... },
   ...
}
daniel
  • 34,281
  • 39
  • 104
  • 158
  • Quick answer below. If you add some sample JSON to your question, I'll update my answer to show how such a secondary index would look. – Frank van Puffelen Jan 14 '16 at 16:05
  • how would a secondary Index look? I added JSON. – daniel Jan 15 '16 at 00:25
  • I have no idea how to invert the index on a generic JSON structure like that. If that was possible, NoSQL database would have a built-in option for doing so. Unless you give some realistic JSON of your data structure, there's nothing I can add. – Frank van Puffelen Jan 15 '16 at 01:27

1 Answers1

1

Does this first query all objects (slow) and then select only the required ones or does firebase optimize the query itself on the server?

Yup, that's pretty much what happens. So this operation will always get slower as you add more items to the location identified by ref.

If that type of performance is a concern (i.e. if you care about scalability), consider adding an inverted/secondary index to the thing that user identified by uid.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • I should also be able to filter the results by adding a `read` security role to firebase which only allows access where `auth.uid==data.child('userid').val()`? I then could just get all without equalto? – daniel Jan 14 '16 at 16:23
  • Firebase security rules cannot be used to filter data, see [this question](http://stackoverflow.com/questions/33606853/firebase-permission-denied-when-reading-data-after-authentication/33612308#33612308), [this one](http://stackoverflow.com/questions/33606853/firebase-permission-denied-when-reading-data-after-authentication/33612308#33612308) and this [section in the Firebase docs](https://www.firebase.com/docs/security/guide/securing-data.html#section-filter). – Frank van Puffelen Jan 14 '16 at 21:53