Chat app NoSQL Firestore Database Schema



To develop a chat application using Firestore Cloud Database, we might have a database schema like this.

4 "root" collections (users, chats, user-chats, chat-messages), these are our "tables" where we will save all the chat data.

Something important in this diagram is the order from top to bottom, it means structures on the top will be created before the ones below.

users collection 

This collection is optional because i have created it to save user information like name, country, etc. you can skip it if you have another way to retrieve user id from users who will chat.



chats collection

In this collection we'll save the chat "room" information, its important because when we create the chat we add a new document to the chats collection, and it will generate a key, and this key will be the chat id.

For this example i will save some fields on the chat document, like last_message_date, last_message_text, timestamp  (to order the data in the query), etc.



user-chat collection

This collection will save N documents for each chat "room", where N means number of people in the chat room.
Explaining: if in the chat room will be 2 person participating, we will create 2 documents on user-chats collection.

the first document will be for the  user who send the first message to the another one, where the document id will be the user id.
Inside the document  we will have one more collection, it will be named chats, in this collection we will save all those chats that the user is in.
And the documents created on chats will have the chat_id as a key. and the same thing, will store some fields like last_massage_date, time, text, timestamp (to sort it in the query). But the thing really important will be the n_unseen field, this field will store the number of messages that the user (who belongs this user-chat) have not seen. And receiver means the information of the another user.


chat-messages collection

Finally we have the last collection, named chat-messages, where all the messages of the chats will be saved, the document created on the chat-messages will be the chat created before on chats collection, related by its key (chat_id),  we will have 1 document per chat room.
Inside the document of chat room, we have another collection named messages, its a collection of all messages sent in the chat, so each document created on the messages collection will be a message, and it will have some fields like date, from, message, time and timestamp.






Comments

Popular posts from this blog

Android/Java: Crear un SplashScreen para nuestra aplicaciĆ³n

Android/Java: Video de fondo en nuestro Login

Solve SecurityError: localStorage is not available for opaque origins React Native