Как получить данные из mongodb и отобразить их в таблице, используя узел JS? - PullRequest
0 голосов
/ 20 мая 2019

У меня проблемы с выяснением, как я могу получить данные в mongodb и извлечь их в файл html / ejs. в файле html / ejs есть одна кнопка, где, если пользователь щелкнет по ней, он отобразит все данные в базе данных коллекции mongodb.

Я нашел несколько вопросов, похожих на мой вопрос, но он не отвечает на мой вопрос. Я все еще новичок в узлах 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 ]

2 голосов
/ 20 мая 2019

Попробуйте следующий код:

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 голос
/ 20 мая 2019

Если вы хотите получить данные из базы данных и хотите отправить их в 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. Теперь вы можете отображать данные, как вы хотите

...