Skip to content
Advertisement

firebase order by datetime desc and asc

so i learn something new from firebase realtime for chat purpose..

but i still confuse how to make an action “how to order by like php”

so i have some code like this

var timenow=moment().format('YYYY-MM-DD HH:m:s');
firebase.database().ref('message/notification').orderByChild("lastupdate").startAt(timenow).on('value',function(snapshot){
listuser.innerHTML+=snapshot.val().name;

});

here my database

How to order limit asc and desc method with lastupdate child? im search for reference that mostly tutorial for android.

Advertisement

Answer

You’re already retrieving the data ordered by their lastupdate and starting at “now”. But your code for then handling the results is incorrect.

In the callback you’ll want to loop over the results from the database with forEach and then add each individual node to the HTML. That’d look something like this:

firebase.database().ref('message/notification').orderByChild("lastupdate").startAt(timenow).on('value',function(snapshot){
  listuser.innerHTML = "";
  snapshot.forEach(function(notificationSnapshot) {
    listuser.innerHTML += notificationSnapshot.val().name;
  });
});

Alternatively, you can listen for the child_added event instead of value, which means that Firebase calls you for each individual child that is added. By listening to child_added and you won’t need the loop in the callback:

firebase.database().ref('message/notification').orderByChild("lastupdate").startAt(timenow).on('child_added',function(snapshot){
  listuser.innerHTML += snapshot.val().name;
});

There is no way to retrieve your data from Firebase in descending order, so you’ll have to reverse it in your application code. The simplest way to do that, is by changing how you add it to the HTML to always prepend the new data to the existing HTML:

listuser.innerHTML = snapshot.val().name + listuser.innerHTML;

Finally: there are many thousands of questions about Firebase already, so it really helps if you can tailor your search to what you need. For example: to find questions about the Realtime Database in JavaScript, I tend to search for the combination of those tags. By adding more terms to the search, you can usually zoom in pretty well. For example: these are questions about querying in descending order.

Advertisement