1

I am building an app with react-native. I would like to sort the chatList by the createdAt value in descending order.

Here is my structure:

{
   "chatList": {
       "L3RDhCUvTVBk--KKgCl" : {
           "lastMessage": {
               "createdAt": 1516638900725
           }
       },
       "L3RDhCUvTVBk--KKgC1" : {
           "lastMessage": {
               "createdAt": 1516638920725
           }
       }
   }
}

Also, do I need to index this structure?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
ykn121
  • 835
  • 1
  • 9
  • 28

1 Answers1

1

If your last message always at lastMessage/createdAt under the chat, (e.g. /chatList/*/lastMessage/createdAt) then you can query the chat lists with:

firebase.database.reference("chatList").orderByChild("lastMessage/createdAt")

You can't get then in descending order though. So you'll either have to reverse the results in the client, or store an inverted timestamp. See my answer here for more on that: firebase -> date order reverse

If the lastMessage is actually dynamic (so different for each child under chatList), then unfortunately you can't get the result from your current structure and you'll need to augment your data to allow the query.

If you want to get a list of chats ordered by their last update date, then you'll need to store precisely that in your database: a list of chats and their last update date.

{
  "chatUpdates": {
    "L3RDhCUvTVBk--KKgCl": 1516638900725
    "L3RDhCUvTVBk--KKgC1": 1516638920725
  }
}

This is an additional data structure, purely to allow your use-case. So now you'll need to update both chatList and chatUpdates when a message is added. To learn more about efficient ways to do that, see How to write denormalized data in Firebase

Some related questions:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Is this syntax for nested properties on ordering formally documented anywhere? If not, that's kind of a doc bug. – Doug Stevenson Jan 22 '18 at 18:21
  • It was introduced at the same time as multi-location updates: https://firebase.googleblog.com/2015/09/introducing-multi-location-updates-and_86.html and present in the old docs: https://www.firebase.com/docs/web/guide/retrieving-data.html#section-queries. But it's indeed completely missing from the docs today, so... yeah.... time to [file a bug report](https://firebase.google.com/support/contact/bugs-features/). – Frank van Puffelen Jan 22 '18 at 18:28
  • I have tried to use `firebase.database.reference("chatList").orderByChild("lastMessage/createdAt")`. However, the response is not sorted – ykn121 Jan 27 '18 at 09:21
  • Is there something else I need to do to really sort the `chatList`? like `.indexOn`, etc. – ykn121 Jan 27 '18 at 10:06
  • Please update your question to show the code that you've tried, including how you handle the snapshot. – Frank van Puffelen Jan 27 '18 at 15:14