【问题标题】:Sort data by timestamp in firebase realtime database在firebase实时数据库中按时间戳对数据进行排序
【发布时间】:2020-03-25 11:18:48
【问题描述】:

我已将数据存储在 firebase 实时数据库中,如下所示:

{
  "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
  } ]
}

现在我想按时间戳值降序对数据进行排序。怎么办?

我在下面对数据进行排序,但它不起作用。

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

【问题讨论】:

  • 到目前为止您发布的代码看起来不错。它有什么问题?提示:问题可能在于您如何处理snapshot 中的数据,因此您需要发布该代码。显示问题的最简单方法是保持处理相同,但随后 console.log 出现问题,而不是构建/更新 UI。
  • 更新了我的问题...现在可以了吗? @FrankvanPuffelen

标签: javascript firebase firebase-realtime-database


【解决方案1】:

当您在查询中使用 orderByChild('timestamp') 时,Firebase 会按照您请求的顺序返回您请求的子节点。每个子节点都有三条信息:

  • 它的关键。
  • 它的价值。
  • 相对于其他子节点的顺序。

但是当您随后调用snapshot.val() 时,它必须将该信息转换为 JSON,该 JSON 仅用于键和值。因此,此时有关订单的信息将被删除。

要按您请求的顺序处理子项,请使用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);
});

【讨论】:

    猜你喜欢
    • 2021-03-16
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多