How To Fetch Data From MongoDB In MERN?

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:

Full Stack Course Online

Java Full Stack Developer Course Online

MEAN Stack Online Course

Python Full Stack Developer Course

React Full Stack Developer Course

Next Js Certification

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:

  • Setting up an Express server with Mongoose.
  • Creating an API route to query the database.
  • Making an API call from the React frontend using Axios.
  • Displaying the fetched data in a React component.

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.

要查看或添加评论,请登录

Lalit Singh的更多文章

  • What Is A SAP Engine?

    What Is A SAP Engine?

    An SAP Engine is a fundamental component of SAP systems, responsible for processing business logic, managing data, and…

    1 条评论
  • Design Patterns In MERN Stack Development

    Design Patterns In MERN Stack Development

    Introduction Design patterns play a crucial role in MERN stack development by providing structured and reusable…

  • Why Is It Essential To Learn SAP In 2025?

    Why Is It Essential To Learn SAP In 2025?

    Introduction In today's rapidly evolving business environment, mastering SAP (Systems, Applications, and Products) has…

  • How To Use JWT Token In MERN?

    How To Use JWT Token In MERN?

    Introduction JSON Web Token (JWT) is a widely used authentication method in MERN stack applications for securely…

  • What Is The Architecture Of MERN Stack?

    What Is The Architecture Of MERN Stack?

    Introduction The MERN stack is a powerful JavaScript-based framework for building modern web applications. It consists…

  • What Is The Difference Between A Stock Transfer And Transfer Posting?

    What Is The Difference Between A Stock Transfer And Transfer Posting?

    Introduction In SAP Material Management (MM), effective inventory management relies on two key processes: Stock…

  • Why Should People Learn SAP S/4 HANA In 2025?

    Why Should People Learn SAP S/4 HANA In 2025?

    Introduction SAP S/4 HANA, a next-generation ERP solution, transforms how businesses operate in the digital era. Built…

  • How To Execute RFC In SAP?

    How To Execute RFC In SAP?

    Introduction Remote Function Call (RFC) is a critical feature in SAP that enables communication and data exchange…

  • How To Choose The Best Institute For SAP Training?

    How To Choose The Best Institute For SAP Training?

    Introduction In 2025, SAP skills are highly valued as businesses increasingly adopt advanced ERP solutions for…

    1 条评论
  • What is the Flutter Widget Tree, and How Does It Work?

    What is the Flutter Widget Tree, and How Does It Work?

    Flutter is a popular tool for building apps. If you’re learning Flutter, one of the most important things you will…

社区洞察

其他会员也浏览了