Firebase database structure for chat application

前端 未结 1 809
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 20:20

I am trying to structure a firebase database for chat system. What I wanted to achieve is after user successfully logged in, they will see a list of message they have sent t

相关标签:
1条回答
  • 2020-12-19 21:08

    It sounds like you want to:

    1. Have chat "rooms" between users
    2. Show a list of each user's chat rooms, with the latest message for that room

    If those are your requirements, I'd model precisely those in your database.

    So for each chat room (a chat between a certain set of users), model the messages for that room:

    chats: {
      $roomId: {
        $messageId: {
          senderId: "..."
          message: "..."
        }
      }
    }
    

    Now for each user, model a separate list of their chats and the latest message:

    userRooms: {
      $uid: {
        $roomId: {
          "message: "..."
        }
      }
    }
    

    Now whenever a user posts a message to a room, you will need to push that message to /chats/$roomId and for each user in that chat room write the message to /userRooms/$uid/$roomId (overwriting the exiting message there).

    This type of data duplication is known as fanning out data, because you're spreading a single snippet of information over multiple places in the database. It is quite common in NoSQL databases, and is part of the reason they scale so well: they trade write complexity for read performance.

    0 讨论(0)
提交回复
热议问题