Back to our use case. When a user types and sends a message, it’ll be sent to the server, which can perform some logic, and then the server will emit the message to all sockets (other users). Messaging apps are expected to store data between sessions, so we’ll just save the message in the database while it’s being relayed.

The message model could be something like:

{

text: String,

createdAt: Date,

userId: ObjectId,

chatId: ObjectId

}

To keep track of an open chatroom where any number of people can join, an identifier field will be helpful to keep track of the messages. For mobile apps, each device will act as a user and for new users, they will be assigned an id field which should then be kept in the device’s local storage. We can determine if a user has or has not joined the chatroom if there is an id field saved on the device. To deal with multiple chatrooms, some sort of mapping structure should be used so that we know which rooms that user is in if it does exist.

Regarding the persistence I mentioned earlier, when a user joins a room, we should give it any pre-existing messages that are saved in the database for that specific room.

I’ve created a working example of a working messaging app. Big thanks to Farid Safi for his messaging component which made this so much easier. Enjoy!