【问题标题】:How to orderby/sort incoming data from Firebase如何排序/排序来自 Firebase 的传入数据
【发布时间】:2020-09-13 11:57:22
【问题描述】:

我正在开发一个 firebase 和 node.js Express 项目,该项目基本上是一个订购系统。

我想按时间对收到的订单进行排序。我尝试使用 firebase 提供的 Orderby() 函数,但它仍然会弄乱 json 输出中的顺序。

看来这应该可行,我不必事后在我的前端对其进行排序

这是我获取火力基地的路线

// route for database 
router.get("/orderslist", (req, res) => {    

  let orders = []
  let number_of_orders

    // Getting the snapshot of the order collection
    db.collection('orders').orderBy('time').get().then( productSnapshot => {
      number_of_orders = productSnapshot.size

      // iterating over the order snapshot
      productSnapshot.forEach(orderDoc => {

        // creating an order object and assigning the ID and the rest of the information from the database
        var order = {
          id: orderDoc.id,
          customer_name: orderDoc.data().customer_name,
          date: orderDoc.data().date,
          comments: orderDoc.data().comments,
          time: orderDoc.data().time,
          total: orderDoc.data().total,
          order_status: orderDoc.data().order_status,
          products: []
        }
        // using the id, to get the products from the subcollection
        db.collection('orders/' + order.id + '/products').get().then( productSnapshot => {

          // iterating over the product snapshot
          productSnapshot.forEach(productDoc => {
            // creating a product object
            var product = {
              name: productDoc.data().name,
              price: productDoc.data().price
            }

            // then we push the product object to the list of products in the order object
            order.products.push(product)

          });

          // we are finished iterating over the productsnapshot and now we can push it to the orders list
          orders.push(order)

          // checks if the list is filled with everything from the database
          if(orders.length == number_of_orders){
            return res.json(orders)
          }

        });

      });

  });

});

这是json中的数据

[
  {
    "id": "xWmlB9fHD4rw8Di75llp",
    "customer_name": "Emil",
    "date": "07/05-2020",
    "comments": "without sugar",
    "time": "a",
    "total": 40,
    "order_status": true,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "GWJoxe0DVFDWfi2AW6jS",
    "customer_name": "test",
    "date": "222222",
    "comments": "",
    "time": "f",
    "total": 10,
    "order_status": false,
    "products": [
      {}
    ]
  },
  {
    "id": "ggYSVKA1i0U8khIpeud4",
    "customer_name": "Oliver",
    "date": "01/05-2020",
    "comments": "order to be packed neatly because im on a bike",
    "time": "d",
    "total": 38,
    "order_status": false,
    "products": [
      {
        "name": "Latte Macchiato",
        "price": 38
      }
    ]
  }
]

【问题讨论】:

  • 我建议添加一个作为unix时间戳的字段,然后您可以按它订购。
  • @Eitank 我按时间排序,这是用于测试的数据类型编号,但仍然不起作用
  • 看起来“时间”是一个字符串而不是一个数字。

标签: node.js json firebase google-cloud-firestore


【解决方案1】:

我建议您创建一个适当的 Firestore 时间戳字段以用作参考,而不是您称为“时间”的字符串字段。

话虽如此,了解 Firestore 时间戳可能很棘手,以下是使用它们的方法。

当您从 Firestore 获取时间戳时,它们属于以下类型:

要将其转换为普通时间戳,您可以使用 .toDate() 函数。

例如,对于如下文档:

我们可以使用类似的东西:

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  console.log(doc.data().[FIELD].toDate());
});

输出如下:

2019-12-16T16:27:33.031Z

现在要进一步处理该时间戳,您可以将其转换为字符串并使用正则表达式根据需要对其进行修改。

例如:(我这里使用的是 Node.js)

db.collection('[COLLECTION]').doc('[DOCUMENT]').get().then(function(doc) {
  var stringified = doc.data().[FIELD].toDate().toISOString();
  //console.log(stringified);
  var split1 = stringified.split('T');
  var date = split1[0].replace(/\-/g, ' ');
  console.log(date);
  var time = split1[1].split('.');
  console.log(time[0]);
});

会给你这样的输出:

现在您可以在查询本身上使用 orderby 方法,也可以在前端获取它们后使用。

一个示例 orderby 如下:

db.collection('[COLLECTION]')
            .orderBy("timeStamp", Query.Direction.ASCENDING)

但是,如果您打算继续使用现有的字符串类型(不推荐),则必须将该字符串转换为数值(可能是 ASCII),以便能够将其作为时间对象正确过滤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2020-01-30
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多