Crhistian Crhistian - 6 months ago 26
Javascript Question

How can I order by child of a child? What options do I have if this is not possible?

The basic structure of the data I'm working with is:

Claims: {
"6B7CBFB4-16EA" : {
"E4A5DB45-C1DE" : {
"ID" : 3,
"Store" : "Staples"
}
}


I also have some example data set up on this firebase https://torrid-inferno-3290.firebaseio.com/Claims as well as a jsfiddle https://jsfiddle.net/8j1zf7vd/

I would like to be able to orderBy ID or Store

The first two levels are randomly generated identifiers. What is currently being done is we are retrieving all of the data under the Claims ref and then sorting it client-side but as the app has grown this is becoming too much so we need to sort and restrict it server side.

If this is not possible and I am only able to query on Child, what is the best way to flatten my data? This will be on a large production app so there will be a lot of data to move around. Does Firebase offer an easy way of accomplishing this?

Answer

There is no way to order on a dynamic grandchild's property in the Firebase Database API. This means that you will have to modify the data structure to match with how your application wants to access it.

One way to do that would be to store the grand-children under their ID, instead of the key you use now:

Claims: {
  "6B7CBFB4-16EA" : {
    "ID_3" : {
      "Key": "E4A5DB45-C1DE"
      "Store" : "Staples"
    }
  }

If you need the data both by your own key and by ID, you could store a mini-index under each claim to allow the lookup:

Claims: {
  "6B7CBFB4-16EA" : {
    "Key_E4A5DB45-C1DE": {
      "ID": 3
      "Store" : "Staples"
    },
    "keysByID": {
      "3" : {
        "Key": "E4A5DB45-C1DE"
      }
    },
    "keysByStore": {
      "Staples": {
        "Key": "E4A5DB45-C1DE"
      }
    }
  }
Comments