为什么使用胡子不会在HTML文件中显示存储在MongoDB中的数据?

问题描述 投票:0回答:1

我正在尝试运行Web应用程序以将数据库的某些数据显示到HTML页面。数据存储在MongoDB数据库中,并使用Mustache显示在HTML页面中。但是,当我尝试运行此程序时,它没有显示任何内容。可能是什么问题?我忘了导入与小胡子有关的东西吗?我是否以错误的方式向HTML发送数据?所有代码都在下面提供。

节点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"}]}
javascript html node.js mongodb mustache
1个回答
0
投票

我试图运行你的代码,现在有一些问题。首先,你试图将所有快递应用程序包装在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"}]});
});
© www.soinside.com 2019 - 2024. All rights reserved.