The Green Foxx The Green Foxx - 1 month ago 22
Javascript Question

Firebase how to sort collection via createdAt field?

I have a collection model that looks like this :

enter image description here

How do I sort the query from latest to oldest via the

createdAt
field.

So far I tried

db.ref('accounts')
.startAt()
.orderByChild('createdAt')
.once('value')
.then(function(snap){
// do shits here...
})


But am getting the data the oldest on top.


  1. January

  2. February

  3. March



But I want


  1. March

  2. February

  3. January


Answer
  1. There is no method to get items sorted in descending order in firebase database. So you need to sort them by ascending and reverse the array in your programming language.

  2. If you want to sort them by time you should be using timestamp instead of datetime as string. In this case you will get wrong ordering because they are actually compared as strings. For example: Imagine this two dates 2016-10-14T02:30:59.653Z, 2016-10-2T02:30:59.653Z. As dates first one is greater but as a strings (lexicographically) second one is greater.

Comments