我正在尝试运行Web应用程序以将数据库的某些数据显示到HTML页面。数据存储在MongoDB数据库中,并使用Mustache显示在HTML页面中。但是,当我尝试运行该程序时,它什么也没显示。可能是什么问题?我忘了进口与胡须有关的东西吗?我是否以错误的方式将数据发送到HTML?所有代码都在下面提供。
Node JS代码:
var express = require("express"),
consolidate = require("consolidate"),
MongoClient = require("mongodb").MongoClient,
Server = require("mongodb").Server;
var app = express();
var errMsg = "";
var name = "";
app.engine('html', consolidate.hogan);
app.set("views", "static");
MongoClient.connect("mongodb://localhost:27018", { useNewUrlParser: true }, (err, db)=>{
dbo = db.db("incidents_db");
if(err) throw err;
app.get("/", function(req, res){
dbo.collection("incidents").find((err, doc) =>{
if(err) throw err;
res.render("main.html", doc);
});
});
app.get("/incident", function(req, res){
res.render("incident.html", {username: name});
});
app.get("/authentication", function(req, res){
res.render("authentication.html", {errMsg: errMsg});
});
app.use(express.static('main'));
app.listen(8080);
});
HTML代码(表):
<table>
<thead>
<th class="th1">Description</th>
<th class="th2">Address</th>
<th class="th3">Reported by</th>
<th >Date</th>
</thead>
{{#incidents}}
<tr>
<td class="th1">{{description}}</td>
<td class="th2">{{address}}</td>
<td class="th3">{{author}}</td>
<td class="th4">{{date}}</td>
</tr>
{{/incidents}}
</table>
JSON对象
{"incidents":[
{"description": "This is a example of report.",
"address": "5th Street",
"author": "Bob",
"date": "16/02/19"}]}
答案 0 :(得分:0)
我尝试运行您的代码,现在有一些问题。首先,您尝试将所有Express应用程序包装在MongoClient.connect()
回调中。您想要执行的操作可能会连接到数据库并首先对其进行初始化。初始化后,您将可以在路线中进行查询。
您可以通过初始化变量,然后为它分配光标来实现。
var database;
MongoClient.connect("mongodb://localhost:27018/incidents_db", {
useNewUrlParser: true
},
(err, db) => {
if(err) throw err;
database = db;
});
如果您需要有关如何执行此操作的说明,可以检查问题How can I connect to mongodb using express without mongoose?
然后,您可以在路由器中引用数据库。
app.get("/", function(req, res){
database.collection("incidents").find((err, doc) =>{
if(err) throw err;
res.render("main.html", {'incidents': doc });
});
});
app.use(express.static('main'));
app.listen(8080);
您正在将视图目录设置为static
吗?您是否有一个包含main.html的文件夹?如果没有,将不会呈现任何内容。
如果mongo连接失败,您可以尝试将对象直接传递到视图模板,并查看显示的值是否符合您的预期。
app.get("/incident", function(req, res){
res.render("incident.html", {"incidents":[
{"description": "This is a example of report.",
"address": "5th Street",
"author": "Bob",
"date": "16/02/19"}]});
});