代码是这样设置的:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
function getData(){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(res);
});
});
当我运行代码并尝试在运行时访问/renderChart 时,我收到“ReferenceError: db is not defined”。我遇到过类似的情况,认为可能是异步调用 mongodb.connect() 导致的类似问题,但我无法使其工作:
Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
最佳答案
这里的问题是你没有将 db
传递给函数,所以它是 undefined
。
解决方案:
function getData(db, res){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(db, res);
});
});
您可能还需要在某些时候传递 req
,或者进行特定的数据库查询。您可能希望使用 promises 或 async/await 来更好地处理所有异步调用。
关于javascript - 表达 js,mongodb : “ReferenceError: db is not defined” when calling a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256936/