Learn How to display database records on fronted browser using EJS view engine in express js. In this article video you will learn about mongodb, express js and EJS template view engine also how user can render MongoDB database table records in html view dynamically using EJS View engine and express js.
For render database records into html table, you need to define GET or POST route in your index.js route file. Copy and Paste below route get method code to display records:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var express = require('express'); var empModel = require('../modules/employee'); var router = express.Router(); var employee =empModel.find({}); /* GET home page. */ router.get('/', function(req, res, next) { employee.exec(function(err,data){ if(err) throw err; res.render('index', { title: 'Employee Records', records:data }); }); }); |
Here empModel = require(‘../modules/employee’); is a custom employee modules.
After this you need to create index.ejs file in views folder and copy and paste the following html table code:
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<table class="table table-striped table-primary"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Emp Type</th> <th>Hourly Rate</th> <th>Total Hours</th> <th>Total Amount</th> </tr> </thead> <tbody> <%if (records.length >0){ %> <% records.forEach(function(row){ %> <tr> <td><%= row.name %></td> <td><%= row.email %></td> <td><%= row.etype %></td> <td><%= row.hourlyrate %></td> <td><%= row.totalHour %></td> <td><%= row.total %></td> </tr> <% })}else{ %> <tr> <td colspan="6">No Record Found</td> </tr> <% } %> </tbody> </table> |
If you will like our video or if you think this video is useful for you the please view and subscribe our YouTube channel for latest video updates. So don’t forget to click bell icon after subscribe our channel.
Follow Tutorialswebsite:
https://www.facebook.com/tutorialswebsite
https://twitter.com/techwebsitetrix
Also See: Insert Records into Mongodb Database Using HTML Form with expressjs
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co