Open In App

How To Connect MongoDB with ReactJS?

Last Updated : 14 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a popular NoSQL database known for its scalability, flexibility, and high performance. When building modern web applications with ReactJS, it’s common to connect your frontend with a backend server that interacts with a database like MongoDB.

Prerequisite

Approach to connect MongoDB with ReactJS

To connect MongoDB with ReactJS, the process is divided into two main steps:

  • Server-Side Connection: Set up a backend using Node.js and Express to connect to MongoDB. The backend will manage all database operations and expose APIs.
  • ReactJS Client: The React frontend makes API calls to the backend to interact with MongoDB, allowing the frontend to fetch, create, update, or delete data from the database.

Connecting MongoDB with ReactJS is key for building data-driven full-stack applications. If you’re interested in mastering database connections in Node.js while working with React, the Full Stack Development with React and Node JS course provides practical insights into integrating MongoDB with full-stack applications.

Steps to Connect MongoDB with React JS

1. Create React App

To build a React application follow the below steps:

  • Step 1: Create a react application using the following command  
npx create-react-app foldername
  • Step 2: Once it is done change your directory to the newly created application using the following command  
cd foldername
  • Step to run the application: Enter the following command to run the application.
npm start

Frontend Code:

JavaScript
// Frontend code 
// Filename - App.js

import { useState } from 'react'
function App() {
    const [name, setName] = useState("");
    const [email, setEmail] = useState("");
    const handleOnSubmit = async (e) => {
        e.preventDefault();
        let result = await fetch(
        'http://localhost:5000/register', {
            method: "post",
            body: JSON.stringify({ name, email }),
            headers: {
                'Content-Type': 'application/json'
            }
        })
        result = await result.json();
        console.warn(result);
        if (result) {
            alert("Data saved successfully");
            setEmail("");
            setName("");
        }
    }
    return (
        <>
            <h1>This is React WebApp </h1>
            <form action="">
                <input type="text" placeholder="name" 
                value={name} onChange={(e) => setName(e.target.value)} />
                <input type="email" placeholder="email" 
                value={email} onChange={(e) => setEmail(e.target.value)} />
                <button type="submit" 
                onClick={handleOnSubmit}>submit</button>
            </form>

        </>
    );
}

export default App;

Note: React is a front-end framework used to build user interfaces, but it cannot directly connect to databases or handle data operations. Therefore, a backend server is required to manage these tasks.

2. Backend Setup With NodeJS

Setup NodeJs for Backend to integrate with frontend:

  • Step1: Make a folder in the root directory using the following command
mkdir backend

Step 2: Once it is done change your directory to the newly created folder called backend using the following command

cd backend
  • Step 3: Run the following command to create configure file
npm init -y 
  •  Step 3: Now Install the mongoose MongoDB using the following command.
npm i express mongoose mongodb cors
  • Step 4: Create a file that is index.js
touch index.js
  • Step to run the application: Enter the following command to run the application.
nodemon index.js 

Application Structure

Project Structure

Dependencies list for frontent server.

{
    "name": "mongosetup",
    "version": "0.1.0",
    "private": true,
    "dependencies": {
        "@testing-library/jest-dom": "^5.17.0",
        "@testing-library/react": "^13.4.0",
        "@testing-library/user-event": "^13.5.0",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-scripts": "5.0.1",
        "web-vitals": "^2.1.4"
    }
}

Dependencies list for backend server.

"dependencies": {
        "cors": "^2.8.5",
        "express": "^4.18.2",
        "mongodb": "^6.1.0",
        "mongoose": "^7.6.1"
}

Backend Code:

JavaScript
// backend/index.js

const mongoose = require('mongoose');
const express = require('express');
const cors = require("cors");

const app = express();

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/yourDB-name', {
    useNewUrlParser: true,
    useUnifiedTopology: true
}).then(() => {
    console.log('Connected to yourDB-name database');
}).catch((err) => {
    console.log('Error connecting to database', err);
});

// Schema for users of the app
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
        unique: true,
    },
    date: {
        type: Date,
        default: Date.now,
    },
});

const User = mongoose.model('users', UserSchema);

// Express setup
app.use(express.json());
app.use(cors({
    origin: 'http://localhost:3000' // React frontend URL
}));

// Sample route to check if the backend is working
app.get("/", (req, resp) => {
    resp.send("App is working");
});

// API to register a user
app.post("/register", async (req, resp) => {
    try {
        const user = new User(req.body);
        let result = await user.save();
        if (result) {
            delete result.password; // Ensure you're not sending sensitive info
            resp.status(201).send(result); // Send successful response
        } else {
            console.log("User already registered");
            resp.status(400).send("User already registered");
        }
    } catch (e) {
        resp.status(500).send({ message: "Something went wrong", error: e.message });
    }
});

// Start the server
app.listen(5000, () => {
    console.log("App is running on port 5000");
});

Step to run the application:

  • Step 1: Enter the following command to run the application in Project directory.
npm start
  • Step 2: Use this command in backend directory to run backend server
nodemon index.js

Output

Conclusion

Connecting MongoDB with ReactJS requires setting up a Node.js backend with Express to manage database operations. The React frontend communicates with this backend using API calls (usually with Axios) to fetch, create, update, or delete data in MongoDB. This full-stack setup allows seamless interaction between the frontend and database, enabling dynamic web applications.



Next Article

Similar Reads