0

I have a Firebase Realtime Database with a very simple structure as follows:

users
  $username
    added: timestamp
    gender: m or f

Image of the structure

What I want to do is to load the users into the browser, filtered by gender and sorted by timestamps. I filter the gender like so:

firebase.database().ref('/users/').orderByChild('gender').equalTo('m').once('value', ...)

but the data is still sorted lexicographically by the $username. How can I change the order? Is there a rule to change serverside sorting from the key of $username to sorting by a childs value?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Tim
  • 45
  • 7
  • Since you call `.orderByChild('gender')`, the results are ordered by the value of each child's `gender` property. If that's not how you're seeing them output, edit your question to show how you process the results. – Frank van Puffelen Jun 04 '20 at 02:16
  • Firebase Database queries can only order/filter on a single property. In many cases it is possible to combine the values you want to order/filter on into a single (synthetic) property. For example, you could order/filter on `"gender_name": "m_rarebone"` and then `.startAt("m").endAt("m~)`. For another example of this and other approaches, see my answer here: https://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase – Frank van Puffelen Jun 04 '20 at 02:18
  • Thank you Frank, your second comment seems to do it for me. Just to be sure, can I tell Firebase to store my $username nodes in a different order than sorted alphabetically? Like sorted by the timestamp instead, serverside. – Tim Jun 04 '20 at 05:18
  • How Firebase stores nodes is non-configurable, but it doesn't really matter here anyway. What matters is how they returned, which is in order of ascending keys by default, unless you specify an `orderBy...()` in the query. – Frank van Puffelen Jun 04 '20 at 13:54

0 Answers0