7

i have a data structure as following at the url www.example.firebase.com/

{
  "companyList" : {
        "compkey1" : {
        "url1":"somelink1",
        "url2":somelink2
         },
         "compkey2" : {
         "url1":"somelink1",
         "url2":"somelink2"
         }
   }
}

What i want to achieve is that i want firebase to return first the list of companies which is

  compkey1
  compkey2

and not any child data

then if the user want to see a specific company i want them to go to that url like so

  www.example.firebase.com/companyList/compkey2

new to firebase so explain as such.

krv
  • 2,830
  • 7
  • 40
  • 79

2 Answers2

6

The Firebase JavaScript client always retrieves complete nodes. It has no option to retrieve only the keys.

If you want to retrieve only the keys/names of the company, you'll have to store them in a separate node.

{
  "companyList" : {
     "compkey1" : {
        "url1":"somelink1",
        "url2":"somelink2"
     },
      "compkey2" : {
         "url1":"somelink1",
         "url2":"somelink2"
     }
  },
  "companyKeys" : {
     "compkey1": true,
     "compkey2": true
  }
}

A common recommendation in Firebase (and many other NoSQL databases) is to model your data in a way that your application will need to read it. In the above example, it seems like you need to read a list of company keys, so that is what you should model.

Note: the Firebase REST API does have a shallow=true parameter that will return only the keys. But I recommend solving the problem by modeling the data differently instead.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • i am looking queries for firebase but at https://www.firebase.com/blog/2013-10-01-queries-part-one.html but can't figure out what i want to achieve..will try what you suggested – krv Jul 27 '15 at 03:27
  • That post is old, Firebase has improved its querying capabilities since then. I'd recommend reading the entire guide on the Firebase site, before trying most other things. – Frank van Puffelen Jul 27 '15 at 03:32
  • 1
    @FrankvanPuffelen do you have any suggestions as to where to start (regarding this topic)? Because 'the entire guide' is a bit much :) – REJH Mar 28 '17 at 07:07
2

Firebase has a shallow parameter which can retrieve only the keys. I verified it's way faster (by a factor of 100), than retrieving the whole nodes.

Here it is in Google App Script (sorry):

class FirebaseNamespace {

  get database() {
    if(!this._database) {
      var firebaseUrl = "https://mydatabase.firebaseio.com/";
      var secret = "mysecret";
      this._database = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
    }
    return this._database;
  }

  get(path, parameters) {
    return this.database.getData(path, parameters);
  }

  keys(path) {
    return Object.keys(this.get(path, {shallow:true}));
  }

  save(path, value) {
    this.database.setData(path, value);
    return value;
  }

}
toddmo
  • 20,682
  • 14
  • 97
  • 107