Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firebase getting only keys then getting data

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.

like image 626
krv Avatar asked Jul 26 '15 14:07

krv


2 Answers

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.

like image 99
Frank van Puffelen Avatar answered Sep 21 '22 19:09

Frank van Puffelen


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;
  }

}
like image 39
toddmo Avatar answered Sep 22 '22 19:09

toddmo