How do you fetch data from mongodb in node js and display in ejs?

I'm having trouble figuring out how can I retrieve data in mongodb and fetch it in an html/ejs file. in html/ejs file there is one button where if the user click it, it will display all data in database collection mongodb.

I found some questions similar to my question but it doesn't answer my question. I am still new at node js and mongodb so I don't really have an Idea on how can I achieve my goal.

this is my index.js

var express = require("express");

var app = express();
app.set('view engine', 'ejs')
//var hostname = '127.0.0.1';
var port = 3000;
var mongoose = require("mongoose");
app.set('view engine','jade');
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/commuters", {useNewUrlParser: true});

app.use('/gui', express.static('gui'));
//use to link static file in the folder named public
var nameSchema = new mongoose.Schema({
    route : String,
      origin : String,
      destination : String,
      estimatedTimeOfArrival : String,
      date : String,
      time : String
  },
  {
      collection : 'boardingAlight'
  });
  //collection is the name of collection that you created in the same database name above
  var User = mongoose.model("User", nameSchema);

 var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true, useNewUrlParser : true }));

app.use("/", (req, res) => {
    res.sendFile(__dirname + "/gui/index.html");
  });
//FOR PORT CONNECTION
//localhost:3000
app.listen(port, () => {
  console.log("Server listening on port " + port);
});

once I created ejs file with a button, I need to display the all the data in a table. Thank you!

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.

How do you fetch data from mongodb in node js and display in ejs?

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

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




  
  
  
 



    
<% if(userData.length!=0){ var i=1; userData.forEach(function(data){ %> <% i++; }) %> <% } else{ %> <% } %>
S.N Full Name Email Address City Country Edit Delete
<%=i; %> <%=data.full_name %> <%=data.email_adress %> <%=data.city %> <%=data.country %> Edit Delete
No Data Found

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.

How fetch data from database in node JS and display in EJS?

How to Fetch & Display Data From MySQL Database in Node js Express.
Step 1 – Create Node Express js App..
Step 2 – Create Table in MySQL Database and Connect App to DB..
Step 3 – Install express flash ejs body-parser mysql Modules..
Step 4 – Create HTML Markup Form..
Step 5 – Import Modules in App.js and Create Routes..

How do you fetch data from MongoDB and display in react?

“get data from mongodb in node js react” Code Answer's.
app. post('/stored', (req, res) => {.
console. log(req. body);.
db. collection('quotes'). insertOne(req. body, (err, data) => {.
if(err) return console. log(err);.
res. send(('saved to db: ' + data));.

How display MongoDB data in HTML?

You have to follow the below steps to display MongoDB data on the HTML page:.
Create Node Express js App..
Install express flash ejs body-parser mongoose dependencies..
Connect App to MongoDB..
Create Model..
Create Routes..
Create HTML Table and Display List..
Import Modules in App. js..
Start App Server..

How do we retrieve data from MongoDB?

You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.