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
ch14folder to a newch15folder, as follows:$ cp -R ch14 ch15
- Open the new
ch15folder in VS Code. - Create a new
backend/src/db/models/message.jsfile. - 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, aroomthat it was sent in, and asentdate for when the message was sent:Â Â username...