Storing and replaying messages using MongoDB
Currently, if a new user joins the chat, they will not see any messages until someone actively sends messages. As such, new users will not be able to participate well in ongoing discussions. To solve this issue, we can store messages in the database and replay them when a user joins.
Creating the Mongoose schema
Follow these steps to create a Mongoose schema for storing chat messages:
- Copy the existing
ch14
folder to a newch15
folder, as follows:$ cp -R ch14 ch15
- Open the new
ch15
folder in VS Code. - Create a new
backend/src/db/models/message.js
file. - Inside it, define a new
messageSchema
, which we are going to use to store chat messages in the database:import mongoose, { Schema } from 'mongoose' const messageSchema = new Schema({
- The message schema should contain
username
(person who sent the message),message
, aroom
that it was sent in, and asent
date for when the message was sent:username...