【发布时间】: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