1

I want to order my query based on the 'order_date' value. Unfortunately, it is returning them in the reverse order (oldest orders first). I am also trying to accomplish this with pagination. This is my current query.

var orders = fbdatabase.ref('orders').orderByChild('order_date');
orders.on('value', function(snapshot) {
  console.log(snapshot.val())
});
clayjones94
  • 2,648
  • 17
  • 26

2 Answers2

1

There is no way to query in reverse order with Firebase. You'll need to use limitToLast:

var orders = fbdatabase.ref('orders')
  .orderByChild('order_date')
  .limitToLast(20);

orders.on('value', function(snapshot) {
  console.log(snapshot.val().reverse());
});

Alternatively, you could store an additional field like order_date_desc that uses a negative value (assuming timestamp).

Michael Bleigh
  • 25,334
  • 2
  • 79
  • 85
1

In addition to Michael's answer, you're also not retaining the order in your callback. It's important to loop over the snapshot using snapshot.forEach() before calling .val():

var orders = fbdatabase.ref('orders').orderByChild('inverted_order_date');
orders.on('value', function(snapshot) {
  snapshot.forEach(function(order) {
    console.log(order.val())
  });
});

See

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807