【问题标题】:Pass variable from JavaScript to pug将变量从 JavaScript 传递给 pug
【发布时间】:2016-12-21 11:33:16
【问题描述】:

我正在使用 Express 脚手架试验 Node.js 和 MongoDB。

我正在努力实现以下目标:

  1. 连接到 MongoDB 并从集合中拉出一个文档(我已经设法做到了)。
  2. 将返回的文档显示为 html(这是我需要帮助的部分)。

我的 index.js 文件如下所示:

var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient, assert = require('assert');

/* GET home page. */
router.get('/', function(req, res, next) {
    MongoClient.connect('mongodb://localhost:27017/beetleJuice', function (err, db) {

        assert.equal(null, err);

        // assign the bugs collection to var col
        var col = db.collection('bugs');

        col.findOne({"assignee" : "John Smith"}, function (err, doc) {

            assert.equal(null, err);

            // Print the resulting document to the console
            console.log("Here is my doc: %j", doc);

            // Close the connection to the database
            db.close();
        }); 
    });

    res.render('index'); // How do I pass the doc over to index.jade?
});

module.exports = router;

我的假设是我可以通过以下方式传递 doc 变量:

res.render('index', doc); 

但是,当我尝试此操作时,我收到一条错误消息,指出未定义 doc

关于我在这里做错了什么有什么建议吗?

【问题讨论】:

  • 您在其范围之外调用“doc”。将 res.render('index', doc) 移到 db.close() 之前
  • 感谢@felix,成功了!

标签: javascript node.js mongodb pug


【解决方案1】:

感谢felix 的评论,解决方案是将 res.render 移到 findOne 函数的回调中:

    col.findOne({"assignee" : "John Smith"}, function (err, doc) {

        assert.equal(null, err);

        // Print the resulting document to the console
        console.log("Here is my doc: %j", doc);

        res.render('index', doc);

        // Close the connection to the database
        db.close();

    }); 
});

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 2017-05-22
    • 2021-12-31
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多