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: