【发布时间】:2016-12-21 11:33:16
【问题描述】:
我正在使用 Express 脚手架试验 Node.js 和 MongoDB。
我正在努力实现以下目标:
- 连接到 MongoDB 并从集合中拉出一个文档(我已经设法做到了)。
- 将返回的文档显示为 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