Displaying Posts in Descending Posted Order with Firebase
As you're working with Firebase to enable user commenting through push, you're seeking a way to display the retrieved data in descending posted order, reversing the default oldest-to-newest ordering.
Firebase offers two methods for retrieving child nodes: by name and by priority. The default order is lexicographic by name, which ensures chronological ordering when using push() to generate child names.
Solution 1: Inverting Timestamp as Priority
To achieve the desired order, you can add a child property with an inverted timestamp and order on that instead:
<code class="python">var ref = new Firebase('https://your.firebaseio.com/sell'); var item = ref.push(); item.setWithPriority(yourObject, 0 - Date.now());</code>
Solution 2: Reading in Ascending Order and Inverting on Client
Alternatively, you can retrieve the children in ascending order and invert them on the client side. However, you'll need to modify the retrieval query as follows:
<code class="python">fbl.child('sell').startAt().limitToLast(20).on('child_added', function(fbdata) { console.log(fbdata.exportVal()); })</code>
Using on('child_added') ensures that the last few children added are returned in reverse chronological order. In contrast, on('value') returns them in name order.
Update:
Note that Firebase now allows ordering by any child or by value, providing more flexibility in how you can sort your data.
The above is the detailed content of How to Display Firebase Posts in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!