Introduction

In this guide, you'll learn how to create a real-time chat application using MongoDB as a database and Socket.io for real-time communication. Real-time chat applications are popular for their immediate message delivery. We'll cover the basics of setting up your development environment, creating a Node.js server, implementing the chat functionality, and storing chat messages in MongoDB. Sample code and examples will guide you through the process.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • Node.js and npm (Node Package Manager) installed on your system.
  • An integrated development environment (IDE) or a code editor for writing code.
  • MongoDB installed and running locally or accessible through a connection string.
  • Basic knowledge of JavaScript and web development concepts.

Step 1: Setting Up the Node.js Server

Start by creating a Node.js server that will handle chat connections and messages. You can use Express.js to simplify the setup. Here's a basic example:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Connect to MongoDB
mongoose.connect('mongodb://localhost/chatdb', { useNewUrlParser: true, useUnifiedTopology: true });
// Define a chat message schema
const messageSchema = new mongoose.Schema({
user: String,
text: String,
timestamp: { type: Date, default: Date.now }
});
const Message = mongoose.model('Message', messageSchema);
io.on('connection', (socket) => {
console.log('A user connected.');
socket.on('chat message', (msg) => {
const message = new Message(msg);
message.save((err, savedMsg) => {
if (err) return console.error(err);
io.emit('chat message', savedMsg);
});
});
socket.on('disconnect', () => {
console.log('A user disconnected.');
});
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});

Step 2: Building the Chat Interface with Socket.io

Create a chat interface using HTML, CSS, and JavaScript. Use Socket.io to establish real-time communication between clients and the server. Here's an example of how to send and receive chat messages:

const socket = io();
$('form').submit(() => {
const user = $('#user').val();
const text = $('#message').val();
socket.emit('chat message', { user, text });
$('#message').val('');
return false;
});
socket.on('chat message', (msg) => {
$('#messages').append($('
  • ').text(`${msg.user}: ${msg.text}`));
    });

  • Step 3: Storing Chat Messages in MongoDB

    Store chat messages in MongoDB to create a message history. The server code in Step 1 already handles saving messages to the database. You can now retrieve and display chat history by querying the database and emitting past messages to clients.


    Conclusion

    You've successfully created a real-time chat application with MongoDB and Socket.io. This guide covers the basics of setting up the server, building the chat interface, and storing chat messages in MongoDB. With these foundational skills, you can further enhance your chat application by adding user authentication, room support, and more features.