Lesson 31. Saving Chat Messages

 

Your chat feature is coming together, and you can take it in many directions to improve it. Though the chat feature allows for real-time communication, when you refresh your page, all messages disappear. The next step is persisting these messages in your database. In this lesson, you implement a simple model to represent each chat message. Then you connect that model to the user model, allowing senders to associate with their own messages. Last, you query the database for the most recent messages whenever a page is reloaded. When you complete these steps, the chat will start to resemble ones that you’ve used on familiar websites and in familiar applications.

This lesson covers

  • Creating a message model
  • Saving messages in a socket.io event handler
  • Querying messages upon new socket connections
Consider this

You have a chat page working, finally allowing users to talk to one another. As soon as a user refreshes their page, their chat history is gone. Although this feature could be marketed as a security implementation, it’s impractical. You want to save the message and do so without interrupting the fast-paced, event-driven system on which your chat application functions. In this lesson, you use Mongoose and your existing application structure to support saving and loading chat messages.

31.1. Connecting messages to users

31.2. Displaying user names in chat

31.3. Creating a message model

Summary