0

I am trying to structure a firebase realtime database for group and personal chat app. What I wanted to achieve is after user successfully logged in, they will see a list of message they have sent to different users. Each of the message preview will show the last message. Then, user can select on the message to view the full chat details. My Question is how to Query the Chats by UserId?

I am following data structure below :

{
 
  "chats": {
    "$chatId1": {
      "title": "Historical Tech Pioneers",
      "lastMessage": "ghopper: Relay malfunction found. Cause: moth.",
      "timestamp": 1459361875666,
       userIds:{
                "$userId1":true,
                "$userId2":true
               }

    },
    "$chatId2": { ... },
    "$chatId3": { ... }
  },

  "messages": {
    "$chatId1": {
      "m1": {
        "name": "eclarke",
        "message": "The relay seems to be malfunctioning.",
        "timestamp": 1459361875337
      },
      "m2": { ... },
      "m3": { ... }
    },
    "$chatId2": { ... },
    "$chatId3": { ... }
  }
}
3
  • Your current structure makes it easy to find the users for a given chat ID. It does not however make it easy to find the chat IDs for a given user. To allow that, you'll want to add an additional, inverted top-level structure to the JSON, where you the chats/chat IDs for each UID: user_chats: { "$userId1": { "$chatId1": true, "$chatId2": true }, ... }. Also see the questions I linked. Commented Jan 22, 2022 at 15:45
  • If use user_chats structure , That means I have to attach listener to every chatId ? like this Database.ref().child("chats").child(chatId).onValue Commented Jan 22, 2022 at 16:09
  • That's indeed the most common approach, but you can also consider duplicating the relevant data into the user_chats node (instead of the true I used in my example here). You could even use a last update timestamp as the value instead of true and use changes to that as the trigger to load that chat again. Commented Jan 22, 2022 at 17:07

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.