Sort records in descending order using Firebase

How do I sort records to orderBy records from the last item added to the first. Descending order.

Anyone has any idea? Been googling around and it seems that firebase does not support ordering in descending order

Indeed, they do not support ordering in descending order.

However what you can do, if you want to order based on a timestamp, is to input a negative timestamp in your database, then order using orderByChild(‘timestamp’) => it works great

If it’s ordering another field, that cannot thave a “-” (minus) sign, then you can use a service.

Here is what I do, ordering in descending order from the ordered firebase data:

ng-repeat="data in arrayOfData | orderObjectBy:'field':true" (with true for “descending order”, see below)

and then the service orderObjectBy:

.filter('orderObjectBy', function() {
  return function(items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function(item) {
      filtered.push(item);
    });
    filtered.sort(function (a, b) {
      return (a[field] > b[field] ? 1 : -1);
    });
    if(reverse) filtered.reverse();
    return filtered;
  };
})
3 Likes

Thanks for the negative timestamp idea, wonderful!

I’m using this code:

firebase.database().ref('users').orderByChild('timestamp').limitToLast(10).on("value", (snap) => {
  snap.forEach((childSnap) => {
    var item = childSnap.val();

    if (reverse) items.unshift(item);
    else items.push(item);
  });
});