1

I have a question about sorting. I want to get the first 10 posts added today, this week, and this month (So I have 30 posts total but each 10 posts from a different part of the database). This works perfect but the problem is that I want to sort all of them by voteCount'.

Is there any way to sort them by date and voteCount?

My reference:

const ref = firebase.database().ref('bookmarks')
    .orderByChild('date')
    .startAt(date.end)
    .endAt(date.start)
    .limitToLast(10)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Giel
  • 21
  • 3
  • There can be only one `orderBy` call in a Firebase query. Sometimes you can combine the values into a single property. See http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Dec 12 '16 at 18:18

1 Answers1

1

f you're willing to pad-print the numbers into a string like this you can sort on basically anything:

"sortKey": "9899999-8521969121365-000009692795"

Don't forget Firebase can't sort-descending so you have to deal with that yourself. That's why my sortKey first field is 9899999. The value was actually 100000 but that portion is a descending sort so I'm subtracting it from 9999999.

Also don't forget to add an indexOn in your rules to avoid client-side sorting!

Chad Robinson
  • 4,575
  • 22
  • 27
  • Firebase can sort descending. Kind of. Use negative values. To accomplish it, just keep a positive value in a node for ascending and a negative for descending. Query by the pos node for ascending and the neg node for descending. :-) – Jay Dec 12 '16 at 20:22
  • Right, that's what I'm doing above, subtracting the key value from a base. The important thing is just to know that composite keys end up being strings. In my example above I have such a key, so the trick to still alpha-sort but in descending order is to subtract from a large base, like 999999999. If your keys are simple numerics, you can subtract from 0 (make the number negative, as you noted). – Chad Robinson Dec 13 '16 at 03:19