Should I store chat messages in the chat document or in separate documents in Firestore using Flutter?

Viewed 156

I'm making a real time chat app in Flutter and I've come to a point when I have to decide how I want to store messages in Firestore. I have 3 collections in Firestore, chats, users, and messages.

Firestore collections

I'm currently storing every message as a separate document in the messages collection. A message document looks something like this:

enter image description here

I'm storing the uid of the message sender and the id of the chat that the message was sent to, so later I can make query to Firestore like this:

  // messages is the collection reference
  Stream<QuerySnapshot> getChatMessages(String id) => messages
      .orderBy('sentOn', descending: true)
      .where('sentTo', isEqualTo: id) // gets all the messages that were sent to the given chat id
      .snapshots();

However, this method isn't very good because of the number of reads or writes I have to do to work with my data in Firestore. Another big problem appears when I want to delete the chat and all of it's messages, as I would have to delete every message document separately and if I stored the messages in the chat document it would only be one delete call to Firestore. On the other side, earlier in another project when I stored all messages in a Map, I noticed that it would get quite slow at drawing the messages on the screen as their number increased.

What do you think? Which is the better option? Is there anything I missed or maybe another way to approach the problem? Please let me know.

Thanks. <3

1 Answers

There are several ways you can approach this. One of the ways to do it is:

Store all messages of a particular chat as a sub collection in the chat document.

So you'll have to delete your message collection.

For example:

In the chat collection, if we have a chat document with ID "123", the we can store all the messages of that chat document as a sub collection under the chat document.

This will reduce your number of reads and writes, thereby making your application more performant and fast.

Related