The simplest way of storing chat messages is probably this:
message:
-message1 {
\"user1\"
\"user2\"
\"message\"
\"date\"
}
-message2
-messa
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.