Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting in descending order in Firebase database [duplicate]

There is this list of Books in the Firebase Realtime Database:

[
  {
    title: "Don't Make Me Think",
    upvotes: 110
  },
  {
    title: "The Mythical Man Month",
    upvotes: 111
  },
  {
    title: "Code Complete 2",
    upvotes: 112
  }
]

By default, the query below returns this list in ASC order:

firebase.database().ref('books').orderByChild('upvotes')

How can I query and order them by upvotes DESC instead?

like image 495
hyang123 Avatar asked Jul 27 '17 17:07

hyang123


1 Answers

Unfortunately firebase doesn't allow returning by descending order. I have generally just reversed the order of the results returned client side.

If your data query is too large to sort client side you can do

firebase.database().ref('books').orderByChild('ups').limitToLast(2)

and then invert the results from there. Documentation can be seen here

like image 83
Scott Buckstaff Avatar answered Oct 22 '22 08:10

Scott Buckstaff