Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Connect ReactJS with flask API ?
Next article icon

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

  • React JS
  • Node JS
  • Mongo DB

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
How to Connect ReactJS with flask API ?
author
krcpr007
Improve
Article Tags :
  • MongoDB
  • Node.js
  • ReactJS
  • Web Technologies
  • NodeJS-Questions
  • React-Questions

Similar Reads

  • How To Connect Node with React?
    To connect Node with React, we use React for the frontend (what users see) and Node.js for the backend (where the server logic lives). The frontend sends requests to the backend, and the backend responds with data or actions. There are many ways to connect React with Node.js, like using Axios or Fet
    4 min read
  • How to connect ReactJS with MetaMask ?
    To Connect React JS with MetaMask is important while making Web 3 applications, It will be done with Meta mask wallet which is the most used browser tool for sending and receiving signed transactions . MetaMask is a crypto wallet and a gateway to blockchain DAPP. It is used to connect our app to web
    3 min read
  • How to connect mongodb Server with Node.js ?
    mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction)Parameters: This method accept two parameters as mention
    2 min read
  • How to Connect Django with Reactjs ?
    Connecting Django with React is a common approach for building full-stack applications. Django is used to manage the backend, database, APIs and React handles the User Interface on frontend. Prerequisites:A development machine with any OS (Linux/Windows/Mac).Python 3 installed.Node.js installed (ver
    9 min read
  • How to Connect ReactJS with flask API ?
    Connecting React with Flask API allows us to create a full-stack web application with React handling the user interface at frontend and Flask serving the data in backend. Here React makes the HTTP request to interact with the flask API to perform operations with the database. ApproachTo connect Reac
    4 min read
  • How to use MongoDB Connection String
    MongoDB connection strings are essential for establishing connections between applications and MongoDB databases. These strings contain crucial information such as server addresses, authentication credentials and optional parameters, enabling seamless communication. Understanding the structure and c
    6 min read
  • How to Connect to MongoDB Atlas Using Shell?
    MongoDB is a highly scalable NoSQL database, renowned for its ability to manage vast amounts of complex and unstructured data. Unlike traditional databases that use a tabular format, MongoDB employs a document-oriented approach, storing data in a flexible, JSON-like format. This makes MongoDB highly
    5 min read
  • How to Connect Node to a MongoDB Database ?
    Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
    6 min read
  • How to Connect to a MongoDB Database Using Node.js
    MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
    4 min read
  • Connect MongoDB with Node App using MongooseJS
    The process of integrating MongoDB, a NoSQL database, with a Node.js application using MongooseJS, a MongoDB object modelling tool designed to work in an asynchronous environment. Prerequisites:NodejsnpmMongoDBMongooseJSSteps to connect MongoDB with Node AppFollowing are the steps to connect MongoDB
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences