How To Fetch Data From MongoDB In MERN?
Introduction
Fetching data from MongoDB is a crucial aspect of building dynamic applications in the MERN stack (MongoDB, Express.js, React, Node.js). The backend (Node.js with Express) interacts with MongoDB using Mongoose, while the frontend (React) makes API calls to retrieve and display data. This process enables seamless data management and real-time updates, making applications more interactive. Refer to the MERN Stack Training in Delhi for complete guidance in this area.
In this blog, we’ll walk through setting up a backend API, fetching data, and displaying it in a React component.
How To Fetch Data From MongoDB In MERN?
Fetching data from MongoDB in a MERN (MongoDB, Express.js, React, Node.js) stack involves several steps. The backend (Node.js with Express) communicates with MongoDB using Mongoose, while the frontend (React) makes API calls to retrieve the data.
Step 1: Setting Up the Backend (Node.js & Express)
To fetch data from MongoDB, you need to create an API endpoint in your Express server that queries the database. The MERN Stack Development Course offers the best guidance for aspiring professionals in this field.?
1. Install Dependencies
Ensure you have the required dependencies installed:
“npm install express mongoose cors dotenv”
2. Connect to MongoDB
Create a server.js file and connect to MongoDB using Mongoose:
“const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();
const app = express();
app.use(cors());
app.use(express.json());
// MongoDB Connection
mongoose.connect(process.env.MONGO_URI, {
??? useNewUrlParser: true,
??? useUnifiedTopology: true,
})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));”
Ensure you have a .env file with:
“MONGO_URI=mongodb://localhost:27017/yourDatabase”
3. Define a Mongoose Model
Create a models/User.js file:
“const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
??? name: String,
??? email: String,
??? age: Number
});
module.exports = mongoose.model('User', userSchema);”
4. Create an API Route to Fetch Data
Modify server.js to include a route:
“const User = require('./models/User');
// API to fetch all users
app.get('/users', async (req, res) => {
??? try {
??????? const users = await User.find();
??????? res.json(users);
??? } catch (error) {
??????? res.status(500).json({ message: error.message });
??? }
});”
Related Courses:
领英推荐
Step 2: Fetching Data in the Frontend (React)
Now, let's fetch this data in the React frontend.
1. Install Axios
To make API requests, install Axios:
“npm install axios”
2. Fetch Data in a React Component
Create a Users.js component:
“import React, { useEffect, useState } from 'react';
import axios from 'axios';
const Users = () => {
??? const [users, setUsers] = useState([]);
??? useEffect(() => {
??????? axios.get('https://localhost:5000/users')
??????????? .then(response => setUsers(response.data))
??????????? .catch(error => console.error('Error fetching users:', error));
??? }, []);
??? return (
??????? <div>
??????????? <h2>User List</h2>
??????????? <ul>
??????????????? {users.map(user => (
??????????????????? <li key={user._id}>{user.name} - {user.email} - {user.age} years old</li>
??????????????? ))}
??????????? </ul>
??????? </div>
??? );
};
export default Users;”
3. Display Users in App.js
Modify App.js:
“import React from 'react';
import Users from './Users';
function App() {
??? return (
??????? <div className="App">
??????????? <h1>MERN Stack Fetch Data Example</h1>
??????????? <Users />
??????? </div>
??? );
}
export default App;”
Step 3: Running the Application
Start the Backend:
“node server.js”
(or use nodemon if installed)
Start the Frontend:
“npm start”
Now, your React app should fetch and display data from MongoDB.
In short, fetching data from MongoDB in a MERN stack involves:
Conclusion
Fetching data from MongoDB in a MERN stack involves setting up an Express server, defining Mongoose models, creating API routes, and making Axios calls in React. This enables seamless communication between the backend and frontend, ensuring dynamic data updates. One can refer to the MERN Stack Developer Certification for complete guidance. By following these steps, you can efficiently retrieve and display data, making your application more interactive and responsive. Mastering this process is essential for building full-stack MERN applications.