4

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!

2 Answers 2

6

Try the following code:

app.js

var express = require("express"),
app = express(),
bodyparser = require("body-parser"),
mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/commuters", {useNewUrlParser: true});

app.use(bodyparser.urlencoded({ extended: true }));
app.set("view engine", "ejs");

var schema = new mongoose.Schema({
  route : String,
  origin : String,
  destination : String,
  estimatedTimeOfArrival : String,
  date : String,
  time : String
}) 
var detailsModel = mongoose.model("detailsModel", schema);
app.get("/", function (req, res) {
res.render("index",{ details: null })
})
app.get("/getdetails", function (req, res) {   
detailsModel.find({}, function (err, allDetails) {
    if (err) {
        console.log(err);
    } else {
        res.render("index", { details: allDetails })
    }
})
})
app.listen(3000, "localhost", function () {
console.log("server has started");
})

index.ejs

<div>
<a href="/getdetails">Get Details</a>
</div>
<hr>

<% if(details!=null) { %>
<table>
<tr>
    <th>Route</th>
    <th>origin </th>
    <th>Destination</th>
    <th>EstimatedTimeOfArrival </th>
    <th>Date </th>
    <th>Time</th>
</tr>
<% details.forEach(function(item){ %>
<tr>
    <td><%= item.route%></td>
    <td><%= item.origin %></td>
    <td><%= item.destination%></td>
    <td><%= item.estimatedTimeOfArrival %></td>
    <td><%= item.date%></td>
    <td><%= item.time%></td>

</tr>
<% }) %>
</table>
<% } %>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for this, but I run the code and I don't seem to be getting any data from my mongo database. after clicking get details it only displayed the heading which is Route origin Destination EstimatedTimeOfArrival Date Time
oh sory It was my mistake, I typed colletion in my schema instead of collection that's its not working. I just have one more question, is there a way to filter the output based on time or date? thanks again!
1

If you want to retrieve data from db and want to send it to ejs then you can do it like this:

 app.get('/',(req,res,next) =>{
   //Here fetch data using mongoose query like
   User.find({}, function(err, users) {
   if (err) throw err;
   // object of all the users
   res.render('index',{users:users});
 });

On ejs file:

 <!DOCTYPE html>
 <html>
 <head>
   <title>Welcome to my blog</title>
 </head>
 <body>
   <h1>Users</h1>
   <p><%=users %></p>
</body>
</html>

What you send in object in res.render will be available on your index.ejs file to use.Now you can display data as you want

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.