首页 > 解决方案 > 为什么存储在 MongoDB 中的数据没有通过使用 mustache 显示在 HTML 文件中?

问题描述

我正在尝试运行 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"}]}

标签: javascripthtmlnode.jsmongodbmustache

解决方案


我已尝试运行您的代码,但现在存在一些问题。首先,您试图将所有快速应用程序包装在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);

你正在设置你的views目录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"}]});
});

推荐阅读