【问题标题】:how to fetch data from mongodb and display it in a table using node js?如何从 mongodb 获取数据并使用节点 js 将其显示在表中?
【发布时间】:2019-10-06 12:01:19
【问题描述】:

我无法弄清楚如何在 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 文件,我需要在一个表中显示所有数据。谢谢!

【问题讨论】:

    标签: javascript node.js mongodb ejs


    【解决方案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 文件中可用。现在您可以根据需要显示数据

    【讨论】:

      【解决方案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>
      <% } %>
      

      【讨论】:

      • 谢谢你,但我运行了代码,我似乎没有从我的 mongo 数据库中获取任何数据。点击get details后只显示标题Route origin Destination EstimatedTimeOfArrival Date Time
      • 抱歉,这是我的错误,我在架构中输入了colletion 而不是collection,这不起作用。我还有一个问题,有没有办法根据时间或日期过滤输出?再次感谢!
      猜你喜欢
      • 1970-01-01
      • 2022-01-09
      • 2014-05-18
      • 1970-01-01
      • 2019-04-12
      • 2019-07-31
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多