How to Integrate MongoDB with Your MERN Stack Application: A Step-by-Step Guide
This is a simple guide to connect MongoDB to your MERN stack
app.
MERN stands for MongoDB, Express, React, Node.
This guide is shared by Cloudi5 Technologies, experts
in web development.
Step 1: Set Up MongoDB
You have two options:
- Local
MongoDB: Install it on your computer from mongodb.com.
- MongoDB
Atlas: Use it in the cloud. Go to mongodb.com/cloud/atlas
and create a free account.
Step 2: Create Your Project
In your terminal:
bash
CopyEdit
mkdir my-mern-app
cd my-mern-app
npx create-react-app client
mkdir server
cd server
npm init -y
npm install express mongoose cors dotenv
Now you have:
- client/
for the React frontend
- server/
for the backend
Step 3: Connect to MongoDB
Inside server, create a file called server.js.
Paste this code:
js
CopyEdit
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
app.use(express.json());
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology:
true
}).then(() => {
console.log('MongoDB
connected');
}).catch((error) => {
console.log('Error:',
error);
});
app.listen(5000, () => {
console.log('Server
running on port 5000');
});
Also create a .env file:
ini
CopyEdit
MONGO_URI=your-mongodb-url-here
Step 4: Create a Model
Inside server, make a folder called models.
Create a file User.js:
js
CopyEdit
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String
});
module.exports = mongoose.model('User', userSchema);
Step 5: Add API Routes
Inside server, make a folder called routes.
Create a file userRoutes.js:
js
CopyEdit
const express = require('express');
const router = express.Router();
const User = require('../models/User');
router.post('/add', async (req, res) => {
const newUser = new
User(req.body);
await newUser.save();
res.send('User
added');
});
router.get('/', async (req, res) => {
const users = await
User.find();
res.json(users);
});
module.exports = router;
In server.js, add this:
js
CopyEdit
const userRoutes = require('./routes/userRoutes');
app.use('/api/users', userRoutes);
Step 6: Use the API in React
In your React app:
js
CopyEdit
useEffect(() => {
fetch('/api/users')
.then(res
=> res.json())
.then(data
=> setUsers(data));
}, []);
Done
Now your MERN app is connected to MongoDB.
Cloudi5
Technologies can help you build more powerful apps.
Visit cloudi5.com to learn
more.
%20(1).png)
Comments
Post a Comment