• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Home
  • About Us
  • Django
  • Laravel
  • Interview Questions
  • Tips

CodingStatus

- Learn Coding to Build Web Applications

  • JavaScript
  • jQuery
  • ReactJS
  • Ajax
  • Node.js
  • PHP
  • SQL

Fetch data from MongoDB Using Mongoose and Node.js Express

December 12, 2020 By Md Nurullah 9 Comments

In this tutorial, you will learn to fetch data from MongoDB using Mongoose and Node.js Express with a simple example. This example will give you the best idea to fetch other bulk data from the table. Even you will get a free script to implement it.
This tutorial helps you to write the script in the Express MVC pattern. Even all the script is written with a separate Model, View & controller file that will be very easy to understand. So, You will easily learn How to fetch data from MongoDB Using Mongoose Node.js Express.

fetch data from mongodb using mongoose

Contents

  • How to Fetch Data From MongoDB Using Mongoose
    • 1. Install Express Application
    • 2. Connect Node.js to MongoDB database
    • 3. Create a Model to Fetch Data
    • 4. Create a Controller to Fetch Data
    • 5. Display Data in HTML Table
    • 6. Create a Route to fetch Data
    • 7. Include and Use the Router in app.js
    • 8. Run Node.js app to Fetch Data
    • My Suggestion

How to Fetch Data From MongoDB Using Mongoose

Mongoose is the best solution to fetch MongoDB data. So, You should use it for writing the fetching query. Before getting started, you will have to configure the required things to execute Node.js Express on your computer.

Before getting started, you must configure the following basic steps

  • Install Node.js on your device
  • Install MongoDB Community Server
  • Also, Install MongoDB Compass  and create a Database with the name nodeapp & Collection with the name users
  • Insert Data into MongoDB Table

1. Install Express Application

First of all, you have to  Install Express Application. After that, create the following folders & files

nodeapp/
  |__controllers/
  |     |__fetch-controller.js
  |__models/
  |     |__fetch-model.js
  |__routes/
  |     |__fetch-route.js
  |__views/
  |     |__user-table.ejs
  |__database.js

2. Connect Node.js to MongoDB database

Now, you have to connect Node.js to the MongoDB database using the following script

File Name – database.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/nodeapp', {useNewUrlParser: true});
var conn = mongoose.connection;
conn.on('connected', function() {
    console.log('database is connected successfully');
});
conn.on('disconnected',function(){
    console.log('database is disconnected successfully');
})
conn.on('error', console.error.bind(console, 'connection error:'));
module.exports = conn;

3. Create a Model to Fetch Data

Create a model to fetch data using the following points –

  • Include mongoose module using require('mongoose')
  • Also, Include a MongoDb database connection file using require('../database')
  • Create a schema with collection columns like full_name, email_address, city & country.
  • Pass MongoDB table users & userSchema to the mongoose.model()
  • Write a mongoose query within module.exports{} to fetch data from the MongoDB database

File Name – fetch-model.js

var mongoose=require('mongoose');
var db = require('../database');
// create an schema
var userSchema = new mongoose.Schema({
            full_name: String,
            email_address:String,
            city:String,
            country:String
        });
userTable=mongoose.model('users',userSchema);
        
module.exports={
     
     fetchData:function(callback){
        var userData=userTable.find({});
        userData.exec(function(err, data){
            if(err) throw err;
            return callback(data);
        })
        
     }
}

4. Create a Controller to Fetch Data

Create a controller to fetch data using the following points –

  • Include a model file using require('../models/fetch-model')
  • Create a method fetchData within module.exports{}
  • Write mongoose query within fetchData to fetch data from the MongoDB table and pass to the view with userData

File Name – fetch-controller.js

var fetchModel= require('../models/fetch-model');
module.exports={
 
    fetchData:function(req, res){
      
      fetchModel.fetchData(function(data){
          res.render('user-table',{userData:data});
      })
    }
}

5. Display Data in HTML Table

Display data in an HTML table with the help of fetchData that comes from the controller.

File Name – user-table.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
 <style type="text/css">
     table, td, th {  
     border: 1px solid #ddd;
     text-align: left;
   }
   
   table {
     border-collapse: collapse;
     width: 50%;
    
   }
   .table-data{
       position: relative;
     left:50px;
     top:50px;
   }
   th, td {
     padding: 15px;
   }
 </style>
</head>
<body>
<!--====form section start====-->
    <div class="table-data">
    <table border="1" >
        <tr>
            <th>S.N</th>
            <th>Full Name</th>
            <th>Email Address</th>
            <th>City</th>
            <th>Country</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
        
        <%
        if(userData.length!=0){
        var i=1;
        userData.forEach(function(data){
        %>
        <tr>
            <td><%=i; %></td>
            <td><%=data.full_name %></td>
            <td><%=data.email_adress %></td>
            <td><%=data.city %></td>
            <td><%=data.country %></td>
            <td><a href="/edit/<%=data.id%>">Edit</a></td>
            <td><a href="/delete/<%=data.id%>">Delete</a></td>
        </tr>
        <%  i++; }) %>
        <% } else{ %>
            <tr>
                <td colspan="7">No Data Found</td>
            </tr>
        <% } %>
    </table>
    </div>
</body>
</html>

6. Create a Route to fetch Data

Create a route to fetch data with the help of the following points –

  • Include a controller file using require('../controllers/fetch-controller')
  • Create a route /fetch-data with GET method to fetch data from the MongoDB database

File Name – fetch-route

var express = require('express');
var router = express.Router();
var fetchController= require('../controllers/fetch-controller');

router.get('/fetch-data',fetchController.fetchData);

module.exports = router;

7. Include and Use the Router in app.js

Now, You have to include & use the fetched route in the main root file app.js

File Name – app.js

var fetchRouter = require('./routes/fetch-route');
app.use('/', fetchRouter);

8. Run Node.js app to Fetch Data

First, start the Node.js server. after that, Enter the following URL in your browser to display data in the HTML table

http://localhost:3000/fetch-data

My Suggestion

Dear developers, I hope you have understood the above script, Now you are able to Fetch data from MongoDB using Mongoose and Node.js express

I will share more tutorials on Node.js/Express asap. So, Continue to visit this website.

If you have any doubts or questions. You can directly ask me through the below comment box.

Related Posts:

  • Javascript Interview Questions and Answers for Freshers &…
  • Express MVC Structure - Model, View and Controller
  • Node.js MySQL CRUD Operation with Example
  • MongoDB CRUD Operations Using Node.js Express and Mongoose

Filed Under: Node.js

Hey there, Welcome to CodingStatus. My Name is Md Nurullah from Bihar, India. I'm a Software Engineer. I have been working in the Web Technology field for 3 years. Here, I blog about Web Development & Designing. Even I help developers to build the best Web Applications.

Reader Interactions

Comments

  1. BrianEroxy says

    April 4, 2020 at 12:03 pm

    Good page, Keep up the beneficial work. Thank you.

    Reply
  2. Roshan Tak says

    January 14, 2021 at 2:29 pm

    please also show the app.js file so its easy for us to check.

    Reply
  3. Raaj Kanchan says

    May 8, 2021 at 11:56 am

    You saved my day. Thank you so much for the help. Well I made a simpler version, I hope you like it.

    getAllUsers: function (req, res) {
    var userTable = User;
    var userData = userTable.find({});
    userData.exec(function(error, data){
    if(error) throw error;
    res.send(data);
    });
    },

    Here, I have saved User schema in a different file. And volla, it worked. Thank you again.

    Reply
  4. Eric says

    May 28, 2021 at 6:48 pm

    in your fetch-route example, it shows POST for /fetch-data but this should be a GET (router.get). Just something I noticed when I was following the tutorial.

    var express = require(‘express’);
    var router = express.Router();
    var userController= require(‘../controllers/fetch-controller’);
    router.get(‘/fetch-data’,fetchController.fetchData);
    module.exports = router;

    Reply
    • Md Nurullah says

      June 7, 2021 at 11:45 am

      I have updated.. Thanks for suggestion

      Reply
  5. Anthon says

    May 29, 2021 at 8:20 pm

    Please tell about app.js, because of that I am not able to run the file, I am getting a error please help

    Reply
    • Md Nurullah says

      June 7, 2021 at 11:41 am

      You will get an app.js file with some default code. you have to only put the given code in this file. It will not give any error.
      if you get any error by doing this, please share that error in comment box

      Reply
  6. vishnu says

    June 25, 2021 at 4:30 pm

    in app.js app is not defined
    how can i define the app.get

    Reply
    • Md Nurullah says

      July 17, 2021 at 4:20 pm

      when you install the express app, will get the app.js file by default.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Follow us

  • facebook
  • twitter
  • linkedin

Recent Posts

  • PHP Interview Questions and Answers
  • Upload Multiple Files to Store in MySQL Database Using PHP
  • How to Insert Data Using Ajax in PHP
  • SQL Join 3 Tables – Join Query for Three Tables
  • Load Records on Select Box using Ajax, PHP & MySQL
  • Home
  • About Us
  • Privacy Policy
  • Disclaimer
  • Terms & Conditions
  • Sitemap
  • Contact Us

Copyright © 2022 CodingStatus - All Rights Reserved