In this tutorial, you will learn how to fetch and display data from mongodb database using node js express mongoose.
How to Fetch and Display Data from Mongodb database using Node js
Here are steps:
Step 1 – Create Node Express js App
Execute the following command on terminal to create node js app:
mkdir my-app cd my-app npm init -y
Step 2 – Install express flash ejs body-parser mongoose Modules
Execute the following command on the terminal to express flash ejs body-parser mysql dependencies :
npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install mongoose
Step 3 – Connect App to MongoDB
Create database.js
file in your app root directory, add the following code in it to connect your app to the mongodb database:
var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/test', {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;
Step 4 – Create Model
Create Models directory and inside this directory create userModel.js file; Then add following code into it:
const mongoose = require("../database"); // create an schema var userSchema = new mongoose.Schema({ name: String, email:String }); var userModel=mongoose.model('users',userSchema); module.exports = mongoose.model("Users", userModel);
Step 5 – Create Routes
Create routes in users.js
route file:
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var userModel = require('../models/userModel'); /* GET home page. */ router.get('/', function(req, res, next) { userModel.find((err, docs) => { if (!err) { res.render("list", { data: docs }); } else { console.log('Failed to retrieve the Course List: ' + err); } }); }); module.exports = router;
Step 6 – Create an HTML Table and Display the List
Create list.ejs
file in the views
directory, and create HTML form to display the list in it:
<!DOCTYPE html> <html> <head> <title>fetch data from mongodb using node js and display in html</title> <link rel='stylesheet' href='/stylesheets/style.css' /> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div> <a href="/customers" class="btn btn-info ml-3">Fetch data from mongodb using node js and display in html</a> </div> <!-- <% if (messages.error) { %> <p style="color:red"><%- messages.error %></p> <% } %> --> <% if (messages.success) { %> <p class="alert alert-success mt-4"><%- messages.success %></p> <% } %> <br> <table class="table"> <thead> <tr> <th scope="col">#</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">No user</td> </tr> <% } %> </tbody> </table> </body> </html>
Step 5 – Import Modules in App.js
Import express flash session body-parser mongoose dependencies in app.js; as shown below:
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 usersRouter = 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: '123456catr', resave: false, saveUninitialized: true, cookie: { maxAge: 60000 } })) app.use(flash()); app.use('/list', usersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(404)); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); // port must be set to 3000 because incoming http requests are routed from port 80 to port 8080 app.listen(3000, function () { console.log('Node app is running on port 3000'); }); module.exports = app;
Step 7 – Test Application
You can use the following command to start node js app server:
//run the below command npm start
Type http://127.0.0.1:3000/list
URL in browser and test this application.
Conclusion
In this tutorial, you have learned how to fetch and display data in html list form mongoDB database using mongoose node js express app.