Sort list of ID by ID child in another node in Firebase

I building react-native chatroom feature by using Firebase. I would like to sort the chatList according to the lastMessage createdAt value in another collection.

Here is the sample structure of my current structure chat:

{
   Chatrooms: {
      CHAT_ID_1: {
         messages: [...],
         metadata: {
            lastMessages: {
                createdAt: 1515857717832  //the time
            },
            users: [USER_ID_1, USER_ID_2]
         }
      },
      CHAT_ID_2: {
         messages: [...],
         metadata: {
            lastMessages: {
                createdAt: 1515857717834  //the time
            },
            users: [USER_ID_1, USER_ID_3]
         }
      }
   },
   Users: {
      USER_ID_1: {
         chatList: {
            USER_ID_3: CHAT_ID_2,     
            USER_ID_2: CHAT_ID_1,
         }
      }
   }
}

Since the CHAT_ID_2 has the latest lastMessage createdAt time, it should be the first one in the chatList of USER_ID_1.

I would like to know how to sort this.

1 answer

  • answered 2018-01-13 18:39 Frank van Puffelen

    From what I see there is no way to do a query that gets you the chat rooms that a specific user is in order by last update timestamp.

    Solutions I can quickly think of:

    1. Load the last update timestamp for each room the user is in with a separate call, and then order them client-side.
    2. Store the last update timestamp for each chat room for each user and then do a query.

    I hope the first solution is self-explanatory. While it does require some extra code, it's actually a lot more efficient than most developers think because the calls from the client to the database are pipelined over the same connection.

    The second solution is to add additional data to /Users/$uid/$chatroomid to suit your use-case. So for example:

    Users: {
      USER_ID_1: {
         chatList: {
            CHAT_ID_2: 1515857717834
            CHAT_ID_1: 1515857717832
         }
      }
    }
    

    With this structure you can get the chats in order of most recent update with:

    firebase.database().ref("Users/USER_ID_1/chatList").orderByValue()
    

    But in this case I'd go for option 1 myself. Since the number of chat rooms for each user is likely to be fairly small and the loads don't require queries, it's likely to both perform and scale well.