Open In App
Related Articles

How to connect MongoDB with ReactJS ?

Improve Article
Save Article
Like Article

A well-liked NoSQL database called MongoDB offers a scalable and adaptable way to store and retrieve data. You might need to establish a connection to a MongoDB database while using ReactJS to create a web application in order to get and modify data. We will examine how to link MongoDB with ReactJS in this article.

We must first establish a server-side connection to MongoDB in order to interact with it. Then, from the ReactJS client, we must access APIs to communicate with MongoDB. Let’s divide the procedure into two primary steps: establishing the server-side connection and utilising the ReactJS client to make API calls.


  • NodeJS installed in your system (install)
  • MongoDB installed in your system (install)

Setup Files and Folders: Setting up the required files and folders for the frontend and backend both one by one.

  • 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

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

Project Structure: It will look like the following:

Project Structure

Step to run the application: Enter the following command to run the application.

nodemon index.js 

Example: Now write down the following code in the following files:

Filename: index.js


// To connect with your mongoDB database
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/', {
    dbName: 'yourDB-name',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) :
    console.log('Connected to yourDB-name database'));
// Schema for users of app
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
    email: {
        type: String,
        required: true,
        unique: true,
    date: {
        type: Date,
const User = mongoose.model('users', UserSchema);
// For backend and express
const express = require('express');
const app = express();
const cors = require("cors");
console.log("App listen at port 5000");
app.get("/", (req, resp) => {
    resp.send("App is Working");
    // You can check backend is working or not by
    // entering http://loacalhost:5000
    // If you see App is working means
    // backend working properly
});"/register", async (req, resp) => {
    try {
        const user = new User(req.body);
        let result = await;
        result = result.toObject();
        if (result) {
            delete result.password;
        } else {
            console.log("User already register");
    } catch (e) {
        resp.send("Something Went Wrong");

Filename: App.js


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


successfully connected ReactJs and MongoDB

We connected the React app with MongoDB Database. We take two inputs which are name and email from a user by React app running on 3000 port and then we call the API created by express and NodeJs and send the data to the MongoDB database.

Last Updated : 29 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials