简体   繁体   中英

How to output the firebase snapshot in reverse order?

I am trying to get the latest 3 data from the database and display them in reverse order in the HTML page.

Code:

var refForevent = database.ref('/events/post');

refForevent.orderByChild("intro").limitToLast(3).on('child_added', function(snapshot){
    
    var eventlist = []

    eventlist.push(snapshot)
    console.log(eventlist)

    eventlist.reverse()
            
    document.getElementById("event1date").innerHTML = moment(eventlist[0].intro).format("MMM Do YYYY");
    document.getElementById("event1title").innerHTML = eventlist[0].title;

    document.getElementById("event2date").innerHTML = moment(eventlist[1].intro).format("MMM Do YYYY");
    document.getElementById("event2title").innerHTML = eventlist[1].title;

    document.getElementById("event3date").innerHTML = moment(eventlist[1].intro).format("MMM Do YYYY");
    document.getElementById("event3title").innerHTML = eventlist[1].title;
    
})

Output: Output that I am getting

Database:数据库

I see that the field intro contains a date.

Here is one solution:

  1. Take the value of this field
  2. Remove the hyphen separators (eg from 2020-12-10 you get the number 20201210)
  3. Multiply this number by -1
  4. Store the resulting value in another field
  5. Sort on this field

Alternatively (and more elegant...), use the date to create a Timestamp, multiply it by -1 and use it as explained above, ie store the resulting value in another field and sort on this field.

Since you're listening to the child_added event, your function gets called with each post node that matches the query in the order in which Firebase returns them. So your eventlist will only ever contain one node at a time.

To reverse the items, you can either get Firebase to return the values in reverse order, as Renaud suggest (I'll also link some answers below), or you can listen to all results in once go and then reversing client-side (as your code already seem to be trying). The latter would look something like:

var refForevent = database.ref('/events/post');

refForevent.orderByChild("date").limitToLast(3).on('value', function(results){
    
    var eventlist = []
    results.forEach(function(snapshot) {
        eventlist.push(snapshot.val())
    });

    eventlist.reverse()
    console.log(eventlist);
            
    ...    
})

So this:

  • Listens to the value event, instead of child_added , so that it gets all matching child nodes in one go.
  • If then loops over the results, adding them to the array,
  • It calls .val() on each child snapshot, to get the value from it.

For more on descending sorting, also 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