"how to structure firestore database in chat app?" Code Answer


what you've offered as the first option is close to how you'd model this in a relation database in a tblmessages. such a literal translation is seldom your best option in nosql databases, since they have very different trade-offs. for example, you've already noticed that you need to perform a query on two fields to get the messages between two users.

when modeling data on a nosql database, i usually recommend modeling in your database for what you see on your screen. so if your chat app has the concept of chat rooms (i.e. persistent chats between specific groups of people), i'd model those in your database too.

in cloud firestore that means that you'd have a top-level collection with a document for each chat room, and then a subcollection under each such document with the messages for that chat room:

chatrooms (collection)
  chatroom1 (document)
    messages (collection)
      message1_1 (document)
      message1_2 (document)
  chatroom2 (document)
    messages (collection)
      message2_1 (document)
      message2_2 (document)

with this model you don't need to query to show the messages in a chat room, but can instead just load (all) the messages straight from the subcollection for that room. it also has the advantage that you partition the rooms, meaning that writes can scale much better.

i typically recommend modeling the chat room document ids after the participants in the room, so that you can easily reconstruct the id based on the participants. but there are more valid options for this.

By h_45h on February 11 2022

Answers related to “how to structure firestore database in chat app?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.