Debu
Debu

Reputation: 49

Sort data by timestamp in firebase realtime database

I have stored the data in firebase realtime db like below:

{
  "orders" : [ null, {
    "res_name" : "order test",
    "res_phone" : "1234567890",
    "timestamp" : 1585123988381
  }, {
    "res_name" : "tesst restaurant",
    "res_phone" : "987654321",
    "timestamp" : 1585124001850
  }, {
    "res_name" : "ppp",
    "res_phone" : "9856847758",
    "timestamp" : 1585124624718
  } ]
}

Now I want to sort the data by timestamp value in descending order. How can it be done?

I am doing below to sort the data but it is not working.

firebase.database().ref('orders').orderByChild('timestamp').on('value', function(snapshot) {
    var value = snapshot.val();
    var htmls = [];
    $.each(value, function(index, value){

      if(value){

         htmls.push('<tr><td>'+ value.res_name +'</td><td>'+ value.res_phone +'</td><td>'+ value.timestamp +'</td></tr>')
      lastIndex = index;
    });
    $('#tblId').html(htmls);

Upvotes: 1

Views: 3781

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

When you use orderByChild('timestamp') on a query, Firebase returns the child nodes that you requested in the order that you requested them. It has three pieces of information for each child node:

  • Its key.
  • Its value.
  • Its order relatively to the other child nodes.

But when you then call snapshot.val() it has to convert that information to a JSON, which only has place for the keys and value. So at that point information about the order is dropped.

To process the children in the order you requested them, use snapshot.forEach():

firebase.database().ref('orders').orderByChild('timestamp').on('value', function(snapshot) {
    var value = snapshot.val();
    var htmls = [];
    snapshot.forEach(function(child) {
        let value = child.val();
        htmls.push('<tr><td>'+ value.res_name +'</td><td>'+ value.res_phone +'</td><td>'+ value.timestamp +'</td></tr>')
    });
    $('#tblId').html(htmls);
});

Upvotes: 1

Related Questions