Site icon RemoteStack

Node Js Retrieve Data from MongoDB Database Tutorial

In this tutorial, you will find out how to fetch data collection from the MongoDB database in the Node js application. How to show data in HTML Table component after fetched from MongoDB database in Node.

To retrieve the data list from the mongo database, we will use express js, express view ejs templating engine. To design the table component, we will use the Bootstrap 5 UI component.

We will begin this tutorial from scratch. We will create the node app from absolute starting, show you how to configure ejs view templating in Node, set MongoDB connection in node js locally, create model or database schema, and how to create routes.

After completing this tutorial, you will be able to quickly get data from MongoDB in Node and show it in HTML.

How to Get Data from MongoDB Database in Node Js with Mongoose

Set Up Node Project

In the first step you have to create a new directory.

mkdir node-proxima

Next, move into the application folder:

cd node-proxima

Install Node Packages

Install the express js and use the –view=ejs tag; the EJS simply stands for Embedded Javascript.

It is a simple templating language/engine which helps generate HTML with plain javascript.

npx express --view=ejs

Again type the following command and hit enter to install the following commands:

npm install -g express-generator

npm install

npm install mongoose express-flash express-session body-parser

Build MongoDB Connection

Inside your node project, you have to create the db.js file. This file will have the settings for making the database connection.

Make sure to enter the following code into db.js file.

var mongoose = require('mongoose')
mongoose.connect('mongodb://0.0.0.0:27017/nodedemodb', {
  useNewUrlParser: true,
})
var conn = mongoose.connection
conn.on('connected', function () {
  console.log('Database successfully connected')
})
conn.on('disconnected', function () {
  console.log('Database disconnected ')
})
conn.on('error', console.error.bind(console))
module.exports = conn

Build Mongoose Schema

Next, create the models folder at the root of your application and create the User.js file.

Here we will create the schema for defining the user object type in the database.

Hence, add the given code into the models/UserModel.js file.

var mongoose = require('mongoose')

var db = require('../db')

var userSchema = new mongoose.Schema(
  {
    name: String,
    email: String,
  },
  {
    collection: 'nodedemodb',
  },
)

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)
    })
  },
}

Now, you have to create the controllers folder, then create user-controller.js file into it thereafter add the given code into the file.

var UserModel = require('../models/UserModel')

module.exports = {
  fetchData: function (req, res) {
    UserModel.fetchData(function (data) {
      res.render('index', { data: data })
    })
  },
}

Define Express Routes

Head over to routes/users.js file, place the entire code into the file, we are using mongoose schema to create the routes.

var express = require('express')

var router = express.Router()

var userController = require('../controllers/user-controller')

router.get('/users', userController.fetchData)

module.exports = router;

Set Up Server File

In this step, you have to import body-parser, mongoose and flash session packages inside the app.js file.

var createError = require('http-errors')
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var bodyParser = require('body-parser')
var flash = require('express-flash')
var session = require('express-session')
var routeUser = require('./routes/users')

var app = express()

// view engine setup
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use(
  session({
    secret: 'abcd123456',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 },
  }),
)

app.use(flash())
app.use('/', routeUser)

app.use(function (req, res, next) {
  next(createError(404))
})

app.use(function (err, req, res, next) {
  res.locals.message = err.message
  res.locals.error = req.app.get('env') === 'development' ? err : {}
  res.status(err.status || 500)
  res.render('error')
})

app.listen(4000, function () {
  console.log('App working on: 4000')
})

module.exports = app

Fetch Data in Node

Now, you have to go to views/index.ejs file, in this file we will add the code.

This code will retrieve data from the mongodb database not only but also we will use the bootstrap 5 table component to display the HTML data fetched from the mongo database.

<!DOCTYPE html>
<html>
  <head>
    <title>Node Js Get Data from Mongo Database</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <link rel="stylesheet" href="/stylesheets/style.css" />
  </head>
  <body>
    <h2 class="mb-3">Retrieve data in Node and Show HTML</h2>

    <% if (messages.success) { %>
    <div class="alert alert-success"><%- messages.success %></div>
    <% } %>

    <table class="table mt-3">
      <thead>
        <tr>
          <th scope="col">#ID</th>
          <th scope="col">Name</th>
          <th scope="col">Email</th>
        </tr>
      </thead>
      <tbody>
        <% if(data.length){ for(var i = 0; i< data.length; i++) {%>
        <tr>
          <th scope="row"><%= (i+1) %></th>
          <td><%= data[i].name%></td>
          <td><%= data[i].email%></td>
        </tr>
        <% } }else{ %>
        <tr>
          <td colspan="3">User not found</td>
        </tr>
        <% } %>
      </tbody>
    </table>
  </body>
</html>

Run Node Application

Lastly put the following command on the command prompt and hit enter to execute the command.

npm start

Here is the url that you have to use to view the data on the browser:

http://127.0.0.1:4000/users

Summary

Throughout this guide, we have profoundly described how to retrieve data from the MongoDB database in the node js app.

We looked at how to use mongoose to create a database connection in a node and explored how to create REST API using express for fetching and displaying data in HTML ejs template.

Exit mobile version