How to Retrieve Data from MongoDB Using NodeJS?

MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for the storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).

Mongoose module

This module of Node.js is used for connecting the MongoDB database as well as for manipulating the collections and databases in MongoDB. The Mongoose. connect() method is used for connecting the MongoDB database which is running on a particular server on your machine. We can also use promises, in this method in resolving the object containing all the methods and properties required for collection manipulation and in rejecting the error that occurs during connection.

Prerequisites

Approach for Retrieve Data

1. Install requires dependencies like express for creating server and mongoose for connecting ,fetching and modification in database.

2. Connect to your mongodb database using mongoose.connect() method and provide your database URL.

3. Created dummy data and create mongoose shema like GFGSchema and inset data in database when mongoose.connect() method called.

4. Create a rote called “/” which helps to retrieve data form specified database using find() method which returns array of object.

Project Structure

Project Structure

Steps to Setup Project

Step 1: Create a folder called Demo.

mkdir Demo

Step 2: Inside the root directory(Demo) initialize the app using following command.

cd Demo
npm init -y

Step 3: Install dependencies like mogoose express by following command.

npm i mongoose express

Step 4: Create server.js file inside root directory(Demo) and add the given code below.

mkdir server.js

Updated package.json look like

"dependencies": {
"express": "^4.19.2",
"mongoose": "^8.4.0"
}
JavaScript
//server.js

//require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const app = express();

const port = process.env.PORT || 3000;

mongoose
    .connect("mongodb://localhost:27017/GFGDatabase")
    .then((err) => {

        console.log("Connected to the database");
        addDataToMongodb();
    });
const data = [
    {
        name: "John",
        class: "GFG"
    },
    {
        name: "Doe",
        class: "GFG"
    },
    {
        name: "Smith",
        class: "GFG"
    },
    {
        name: "Peter",
        class: "GFG"
    }
]
const gfgSchema = new mongoose
    .Schema({
        name: { type: String, required: true },
        class: { type: String, required: true },
    });

const GFGCollection = mongoose
    .model("GFGCollection", gfgSchema);

async function addDataToMongodb() {
    await GFGCollection
        .deleteMany();
    await GFGCollection
        .insertMany(data);
    console.log("Data added to MongoDB");
}

app.get('/', async (req, res) => {
    try {
        const data = await GFGCollection.find();
        res.json(data);
        console.log(data);
    } catch (err) {
        console.log(err);
        res.status(500).send("Internal Server Error");
    }
});

app
    .listen(port, () => {
        console.log(`Server is running on port ${port}`);
    });

Steps to run Project:

1. Navigate to root directory (Demo) and run following command.

node server.js

2. Open browser and type URL:

localhost:3000/

Output

Output in Browser

Output in Terminal