Search code examples
sortingfirebasefirebase-realtime-databasepolymer-1.0polymerfire

Sort by key desc in polymerfire with firebase-query


I am using firebase and polymer to build an app, and I have a data I got using the firebase-query element. I want to reorder the data so that it displays the new data first, so I thought I could use the sort attribute on template tag to sort it by the key in a descending order, but it's not working as expected.

     <firebase-query
  id="questionQuery"
  path="/questions"
  limit-to-last="15"
  data="{{questions}}">
</firebase-query>

And the template looks like this method:

        <template is="dom-repeat" items="[[questions]]" sort="_computeSort" as="question"><p>[[question.body]]</p></template>

and inside my element definition, I have this:

  _computeSort: function(a, b) {
    console.log(a.__firebaseKey__);
    if (a.__firebaseKey__ == b.__firebaseKey__) {
      return 0;
    }
    return a.__firebaseKey__ > b.__firebaseKey__ ? -1 : 1;
  },

This is not working. The output of the log to console is just bunch of undefindes, so the problem should be there, but how can I access each question's key?


Solution

  • Okay, I got an anser

    $key is the expression to access the key generated by the firebase, so just change the sorting function to this:

        _computeSort: function(a, b) {
        if (a.$key == b.$key) {
          return 0;
        }
        return a.$key > b.$key ? -1 : 1;
      },
    

    I actually had just copied the code from here Polymer 1.0: Sorting dom-repeat and that's how I ended up with code like _firebasekey__.