我正在使用Express测试Node.js和MongoDB。
我正在努力实现以下目标:
我的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
。
对我做错了什么有什么建议吗?
发布于 2018-10-11 04:29:06
多亏了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();
});
});
https://stackoverflow.com/questions/41261850
复制相似问题