,

Integrating Express with MongoDB for a Real Time Chat App: A MERN Stack Project

Posted by


In this tutorial, we will provide a step-by-step guide on how to connect Express to MongoDB for a Real Time Chat App using the MERN stack (MongoDB, Express, React, Node.js). By the end of this tutorial, you will have a fully functional real-time chat application where users can communicate with each other in real-time.

Requirements:

  1. MongoDB Atlas account: Sign up for a free MongoDB Atlas account at https://www.mongodb.com/cloud/atlas.
  2. Node.js and NPM installed on your machine: Install Node.js and npm from https://nodejs.org/en/.
  3. Create-react-app: Install create-react-app by running npx create-react-app your-app-name in the terminal.

Step 1: Setting up the backend with Express

  1. Create a new folder for your project and navigate into it using the terminal.
  2. Run npm init -y to initialize a new npm project.
  3. Install Express and nodemon to automatically restart the server when changes are made by running npm install express nodemon.
  4. Create a new file called server.js and add the following code:
const express = require('express');
const app = express();
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
  1. Run the server by running npm run start and navigating to http://localhost:5000 in your browser. You should see Hello World! displayed.

Step 2: Connecting Express to MongoDB

  1. Install the mongoose package by running npm install mongoose.
  2. Create a new file called db.js and add the following code:
const mongoose = require('mongoose');

mongoose.connect('your-mongodb-atlas-connection-string', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch((err) => console.log(err));
  1. Replace 'your-mongodb-atlas-connection-string' with the connection string from your MongoDB Atlas dashboard.
  2. Import and call the db.js file in the server.js file:
require('./db');

Step 3: Setting up the frontend with React

  1. Navigate to the project directory and run npx create-react-app client to create a new React project.
  2. Delete the contents of the src directory and create a new file called index.js with the following code:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
  1. Create a new file called App.js and add the following code:
import React from 'react';

const App = () => {
  return (
    <div>
      <h1>Real Time Chat App</h1>
    </div>
  );
};

export default App;
  1. Start the React server by navigating to the client directory and running npm start.

Step 4: Adding real-time chat functionality

  1. Install the socket.io package in the server directory by running npm install socket.io.
  2. Add the following code in the server.js file after the Express app has been initialized:
const http = require('http').createServer(app);
const io = require('socket.io')(http);

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

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

http.listen(5000, () => {
  console.log('Socket.io server running on port 5000');
});
  1. Add the following code in the App.js file to establish a socket connection with the server:
import React, { useEffect } from 'react';
import io from 'socket.io-client';

const socket = io('http://localhost:5000');

const App = () => {
  useEffect(() => {
    socket.on('connect', () => {
      console.log('Connected to server');
    });

    socket.on('disconnect', () => {
      console.log('Disconnected from server');
    });
  }, []);

  return (
    <div>
      <h1>Real Time Chat App</h1>
    </div>
  );
};

export default App;
  1. Test the real-time chat functionality by opening multiple tabs of the application in the browser and sending messages between them.

Congratulations! You have successfully connected Express to MongoDB for a Real Time Chat App using the MERN stack. Happy coding!

0 0 votes
Article Rating

Leave a Reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Monkey-king714
2 hours ago

awesome tutorial sir. thank you

@huyhieunguyen1995
2 hours ago

please complete this course as quickly as possible 🙏

@laluPrasad-hh3js
2 hours ago

post daily 2 videos please

3
0
Would love your thoughts, please comment.x
()
x