,

Integrating Socket.IO with MongoDB for Real-time Chat | Step-by-step Guide with CodeByNaf

Posted by


In this tutorial, we will cover how to connect Socket.IO with MongoDB to create a real-time chat application. Socket.IO is a JavaScript library for real-time web applications that enables bi-directional communication between web clients and servers. MongoDB is a NoSQL database that is commonly used for storing and querying data in real-time applications. By combining these two technologies, we can create a real-time chat application that allows users to send and receive messages in real time.

To get started, make sure you have Node.js and npm installed on your machine. You can download them from the official Node.js website if you haven’t already. Once you have Node.js and npm installed, you can follow the steps below to create the real-time chat application.

Step 1: Set up a new Node.js project
Create a new directory for your project and navigate to it in the terminal. Run the following command to initialize a new Node.js project:

npm init -y

This command will create a new package.json file in your project directory. This file is used to manage dependencies and scripts for your Node.js project.

Step 2: Install the required dependencies
Next, you need to install the required dependencies for the project. Run the following command to install Socket.IO and MongoDB:

npm install socket.io mongodb

Socket.IO is a real-time web socket library, and MongoDB is a NoSQL database that we will use to store chat messages.

Step 3: Set up the MongoDB database
Before we can connect Socket.IO with MongoDB, we need to set up a MongoDB database to store chat messages. You can follow these steps to create a new database and collection in MongoDB:

  1. Install MongoDB on your machine if you haven’t already. You can download MongoDB from the official website and follow the installation instructions for your operating system.
  2. Start the MongoDB server by running the following command in the terminal:
mongod
  1. Open a new terminal window and connect to the MongoDB shell by running the following command:
mongo
  1. Create a new database for the chat application by running the following command in the MongoDB shell:
use chatapp
  1. Create a new collection to store chat messages by running the following command:
db.createCollection('messages')

Now that we have set up the MongoDB database, we can move on to connecting Socket.IO with MongoDB.

Step 4: Create the server-side application
Create a new file called server.js in your project directory and add the following code to set up a basic Express server and Socket.IO connection:

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const { MongoClient } = require('mongodb');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

const url = 'mongodb://localhost:27017';
const dbName = 'chatapp';

MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
  if (err) {
    console.error(err);
    return;
  }

  const db = client.db(dbName);

  io.on('connection', (socket) => {
    console.log('A user connected');

    socket.on('disconnect', () => {
      console.log('A user disconnected');
    });

    socket.on('message', async (data) => {
      await db.collection('messages').insertOne(data);
      io.emit('message', data);
    });
  });

  server.listen(3000, () => {
    console.log('Server is running on port 3000');
  });
});

This code sets up a basic Express server, establishes a Socket.IO connection, and connects to the MongoDB database. When a user sends a message, the message is stored in the MongoDB database and broadcasted to all connected clients using Socket.IO.

Step 5: Create the client-side application
Create a new file called index.html in your project directory and add the following code to create a simple chat interface:

<!DOCTYPE html>
<html>
<head>
  <title>Real-Time Chat</title>
</head>
<body>
  <ul id="messages"></ul>
  <input type="text" id="input" autocomplete="off" />
  <button id="send">Send</button>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
  <script>
    const socket = io.connect();

    socket.on('message', (data) => {
      const messages = document.getElementById('messages');
      const li = document.createElement('li');
      li.appendChild(document.createTextNode(`${data.username}: ${data.message}`));
      messages.appendChild(li);
    });

    document.getElementById('send').addEventListener('click', () => {
      const input = document.getElementById('input');
      const message = input.value;
      const username = 'User';
      socket.emit('message', { username, message });
      input.value = '';
    });
  </script>
</body>
</html>

This code creates a simple chat interface with an input field for sending messages. When a user sends a message, the message is broadcasted to all connected clients using Socket.IO.

Step 6: Start the server and run the application
To start the server, run the following command in the terminal:

node server.js

This command will start the Express server and Socket.IO connection on port 3000.

Open a web browser and navigate to http://localhost:3000 to view the chat interface. You can open multiple browser tabs to simulate multiple chat users and test the real-time chat functionality.

Congrats! You have successfully connected Socket.IO with MongoDB to create a real-time chat application. Feel free to customize and extend the application with additional features, such as user authentication, message history, and chat rooms. Have fun coding! #CodeWithNaf