如何从mongodb获取数据并使用节点js将其显示在表中?

时间:2019-05-20 06:37:00

标签: javascript node.js mongodb ejs

我在弄清楚如何在mongodb中检索数据并将其提取到html / ejs文件中时遇到了麻烦。在html / ejs文件中,有一个按钮,如果用户单击该按钮,它将显示数据库集合mongodb中的所有数据。

我发现了一些与我的问题类似的问题,但没有回答我的问题。我对Node js和mongodb还是很陌生,所以我对如何实现目标没有真正的想法。

这是我的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);
});

使用按钮创建ejs文件后,需要在表中显示所有数据。谢谢!

2 个答案:

答案 0 :(得分:2)

尝试以下代码:

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>
<% } %>

答案 1 :(得分:1)

如果要从db检索数据并将其发送到ejs,则可以这样操作:

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

在ejs文件上:

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

res.render中发送对象的内容将在index.ejs文件上可用。现在,您可以根据需要显示数据