12
votes

i would like to ask if there is a best practice for firestore, when one develops a chat app, and what is the best practice to store messages for chat-rooms.

The assumption here is that every chatroom has its own document.

I started using an array to store the messages from the users. The problem with that approach is that there is no way to add, a insert(append) a new entry everytime a new message is submitted to the chat room. One has to save a new copy of the array with the new message appended. This seems like something that would scale really bad, unless the chat history is split in sub-arrays etc..

In the official documents, they suggest a structure, where one should store the messages of a specific chatroom as separate documents in a sub collection of that chatroom. I wonder if this approach is the best, and what would be some drawbacks, or if there is another preferred way to do this.

2
Storing all messages for a chat room into a single document will quickly lead you to a document larger than the allowed size of 1MB. Using arrays is a bad idea in a multi-user environment, as explained in this blog post. Using a separate document for each chat message seems simplest. Given that the documentation also steers you in that direction, why do you think another approach is better?Frank van Puffelen
no you are right, i just have no experience with nosql databases and i find a lot of things a bit conter intuitive coming from a mysql backgroundJimmy H.

2 Answers

11
votes

I would generally go with the approach of "Every chat room has a subcollection of messages. And every new message is a separate document in this subcollection." This has several advantages: It's easy to add or edit individual messages, and you can perform a number of different queries (like "Grab the 20 most recent messages")

The biggest drawback, I suppose, is that if you find that new users are frequently going to be entering your chat and will want to see the entire chat history of the room up until they joined, that would result in a large number of database reads. Realistically, though, I don't know how often that would happen in real life, and you could mitigate this by using pagination to grab your historical chat in batches.

-1
votes

To add to what Todd said:

In arrays you cannot store Timestamps - a big downside for your case, as you'll want the time the message was sent.