首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将变量从JavaScript传递给pug

将变量从JavaScript传递给pug
EN

Stack Overflow用户
提问于 2016-12-21 19:33:17
回答 1查看 1.3K关注 0票数 0

我正在使用Express测试Node.js和MongoDB。

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

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

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

代码语言:javascript
复制
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变量:

代码语言:javascript
复制
res.render('index', doc); 

然而,当我尝试这样做时,我得到了一个错误,告诉我没有定义doc

对我做错了什么有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2018-10-11 04:29:06

多亏了felix的注释,解决方案是将res.render移到findOne函数的回调中:

代码语言:javascript
复制
    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();

    }); 
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41261850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档