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.
I'm currently storing every message as a separate document in the messages collection.
A message document looks something like this:
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

