How to connect MongoDB with ReactJS ?
Last Updated :
02 Nov, 2023
Connecting MongoDB with React is an important task for making full-stack applications and web apps with databases. 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.
Approach to connect MongoDB with ReactJS
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 utilizing the ReactJS client to make API calls.
Prerequisite
Steps to Connect MongoDB with React JS
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
Step to run the application: Enter the following command to run the application.
nodemon index.js
Application 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"
}
Example: Import and configure mongo in the backend/index.js file and create a form in react App.js component to link the mongo with front end
JavaScript
const mongoose = require( 'mongoose' );
dbName: 'yourDB-name' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) :
console.log( 'Connected to yourDB-name database' ));
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);
User.createIndexes();
const express = require( 'express' );
const app = express();
const cors = require( "cors" );
console.log( "App listen at port 5000" );
app.use(express.json());
app.use(cors());
app.get( "/" , (req, resp) => {
resp.send( "App is Working" );
});
app.post( "/register" , async (req, resp) => {
try {
const user = new User(req.body);
let result = await user.save();
result = result.toObject();
if (result) {
delete result.password;
resp.send(req.body);
console.log(result);
} else {
console.log( "User already register" );
}
} catch (e) {
resp.send( "Something Went Wrong" );
}
});
app.listen(5000);
|
Javascript
import { useState } from 'react'
function App() {
const [name, setName] = useState( "" );
const [email, setEmail] = useState( "" );
const handleOnSubmit = async (e) => {
e.preventDefault();
let result = await fetch(
method: "post" ,
body: JSON.stringify({ name, email }),
headers: {
'Content-Type' : 'application/json'
}
})
result = await result.json();
console.warn(result);
if (result) {
alert( "Data saved succesfully" );
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;
|
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: This output will be visible on https://localhost:3000/ on browser and inside mongo Database.
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...