Node Express MongoDB本地驱动程序 – 在哪里打开数据库连接?
我想在app.js文件中通过Node-Mongo-Native-Driver打开并初始化数据库,然后将其保持打开并读取路由。 我把下面的代码放在app.js文件中,并打包app.gets,以便在打开数据库时使它们可用:
var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("dev-db") , products = db1.collection('products'); app.get('/', routes.index); app.get('/users', user.list); });
当我尝试读取我得到的index.js路由中的数据库时
ReferenceError: products is not defined
我认为index.js应该能够访问产品,因为它是在外部函数中定义的,因为在初始化中包装了app.gets。
除了第二个问题:MongoClient.open和MongoClient.connect有什么区别?
JavaScript使用词法范围 – 意思是说,如果你这样做,它会工作:
var mongoClient = new MongoClient(new Server('localhost', 27017)); mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("dev-db") , products = db1.collection('products'); app.get('/', function closedOverIndexRoute(req, res, next) { console.log(products); // this will work }); app.get('/users', user.list); // however, user.list will not be able to see `products` });
函数不会成为闭包(不保留其封闭函数的值),除非它是在闭包内部进行词汇(书写)。
但是,您可能不希望将整个应用程序编写为一个大closures。 相反,您可以使用导出并要求访问您的产品集合。 例如,在一个名为mongoconnect.js的文件中:
var mongoClient = new MongoClient(new Server('localhost', 27017)); var products; mongoClient.open(function(err, mongoClient) { var db1 = mongoClient.db("dev-db"); products = db1.collection('products'); }); module.exports = { getProducts: function() { return products; } };
然后在你的index.js文件中:
var products = require('mongoconnect').getProducts();
另一种select(如果你想保留应用程序和索引)是使用一对闭包:
index.js:
module.exports = function(products) { return function index(req, res, next) { console.log(products); // will have closed-over scope now }; };
app.js,在mongoClient.open()
里面,定义了products
:
var index = require('./index')(products);