When building modern web applications, developers often use React for the frontend and MongoDB for storing data. But if you’re new to full-stack development, connecting the two might seem a little confusing.
Don’t worry! In this article, we’ll walk through everything step-by-step. You’ll learn how to connect MongoDB with a React app using Node.js and Express as the backend. We’ll keep everything simple and easy to understand.
What is MongoDB?
MongoDB is a NoSQL database that stores data in a flexible, JSON-like format. It’s great for projects where your data structure can change over time. It’s also popular because it works well with JavaScript-based apps.
What is React?
React is a JavaScript library for building user interfaces. It lets you create components and build interactive pages easily.
But React runs on the frontend, and MongoDB runs on the backend. So how do you connect them? That’s where Node.js and Express come in.
Tools You’ll Need
Before we start, make sure you have these installed:
- Node.js and npm (Node Package Manager)
- MongoDB (either locally or using MongoDB Atlas)
- A code editor (like VS Code)
- Postman (for testing APIs – optional)
Step 1: Set Up Your Backend with Node.js and Express
First, let’s create a backend to talk to MongoDB.
1.1 Create a New Project
mkdir backend
cd backend
npm init -y
1.2 Install Required Packages
Install Express and Mongoose (a library to connect to MongoDB):
npm install express mongoose cors
- express – to build the API
- mongoose – to connect and interact with MongoDB
- cors – to allow requests from your React frontend
1.3 Create a Basic Server
In the backend
folder, create a file called server.js
:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const PORT = 5000;
app.use(cors());
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
If you’re using MongoDB Atlas, replace the connection string with your own Atlas URL.
Step 2: Create a MongoDB Model
Let’s say we’re building a simple app to manage a list of users.
Create a new folder called models
and add a file User.js
:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
module.exports = mongoose.model('User', userSchema);
Step 3: Set Up Routes to Handle API Requests
Create a new folder routes
and add a file users.js
:
const express = require('express');
const router = express.Router();
const User = require('../models/User');
// Get all users
router.get('/', async (req, res) => {
const users = await User.find();
res.json(users);
});
// Add a new user
router.post('/', async (req, res) => {
const newUser = new User(req.body);
const savedUser = await newUser.save();
res.json(savedUser);
});
module.exports = router;
In server.js
, import and use the route:
const userRoutes = require('./routes/users');
app.use('/users', userRoutes);
Now your backend is ready!
Step 4: Create the React Frontend
Now let’s build a frontend that connects to the backend.
4.1 Create a New React App
In a new terminal:
npx create-react-app frontend
cd frontend
npm install axios
We’ll use Axios to send HTTP requests.
Step 5: Connect React to the Backend
5.1 Fetch Users from the Server
In App.js
, update the code:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function App() {
const [users, setUsers] = useState([]);
const [form, setForm] = useState({ name: '', email: '' });
useEffect(() => {
axios.get('http://localhost:5000/users')
.then(res => setUsers(res.data))
.catch(err => console.log(err));
}, []);
const handleChange = (e) => {
setForm({ ...form, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
axios.post('http://localhost:5000/users', form)
.then(res => setUsers([...users, res.data]))
.catch(err => console.log(err));
};
return (
<div style={{ padding: '20px' }}>
<h2>User List</h2>
<ul>
{users.map((u, i) => (
<li key={i}>{u.name} - {u.email}</li>
))}
</ul>
<h3>Add User</h3>
<form onSubmit={handleSubmit}>
<input name="name" placeholder="Name" onChange={handleChange} /><br />
<input name="email" placeholder="Email" onChange={handleChange} /><br />
<button type="submit">Add</button>
</form>
</div>
);
}
export default App;
Now when you start both servers (npm start
in the frontend
and node server.js
in the backend
), you’ll be able to view, add, and manage users!
Step 6: Testing and Going Live
- You can test the API with tools like Postman.
- For production, you might host the backend on Render, Vercel, or Heroku.
- MongoDB Atlas lets you host your database online.
Final Thoughts
Using MongoDB with React may sound hard at first, but once you understand the flow, it’s simple:
- React handles the frontend.
- Express and Node.js handle the backend.
- MongoDB stores your data.
With this basic setup, you can now build full-stack applications where users can submit data, view it, and interact with it in real-time.
Summary
Step | What You Did |
---|---|
1 | Set up Node.js + Express server |
2 | Connected MongoDB with Mongoose |
3 | Created user routes and model |
4 | Built frontend with React |
5 | Connected React to backend using Axios |
6 | Tested and ran full-stack app |
This is just the beginning — you can now explore user authentication, file uploads, search filters, and more. Happy coding!