简体   繁体   中英

Using orderByChild Firebase to get most recent posts

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM