Node.js和MongoDB,重用DB对象

我对Node.js和MongoDB都是新手,但是我已经设法将SO和mongo的文档放在一起。

Mongo文档给出了例子:

// Retrieve var MongoClient = require('mongodb').MongoClient; // Connect to the db MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) { if(!err) { console.log("We are connected"); } }); 

这看起来很好,如果我只需要在一个地方使用一个function的数据库。 在SO上search和阅读已经表明,我不应该每次都打开一个新的连接,而是使用一个池并重用我第一次获得的数据库对象。 这个答案很丰富,但我不知道如何获得DB对象,然后如何重用它。

假设我的App.js中有上面的Node.js代码,然后我有不同的路由需要在db上运行不同的操作:

 app.post('/employee', function(req, res){ //Put req.name in database }); app.post('/car', function(req, res){ //Put req.car in database }); 

我将如何将这两个片段放在一起有用?

我在Node.js中发现了一个类似的问题, 重用了MongoDB引用 ,但是从这个( http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html )的外观来看,它看起来像我应该使用MongoClient而不是db()。 而且我不确定它是否解决了我的问题

你总是可以写一个模块来初始化你的数据库连接,并使它们在整个程序中都可以访问。 例如:

mongo.js

 var mongodb = require('mongodb'); module.exports.init = function (callback) { var server = new mongodb.Server("127.0.0.1", 27017, {}); new mongodb.Db('test', server, {w: 1}).open(function (error, client) { //export the client and maybe some collections as a shortcut module.exports.client = client; module.exports.myCollection = new mongodb.Collection(client, 'myCollection'); callback(error); }); }; 

app.js

 var mongo = require('./mongo.js'); //setup express... //initialize the db connection mongo.init(function (error) { if (error) throw error; app.listen(80); //database is initialized, ready to listen for connections }); 

randomFile.js

 var mongo = require('./mongo.js'); module.exports.doInsert = function () { //use the collection object exported by mongo.js mongo.myCollection.insert({test: 'obj'}, {safe:true}, function(err, objects) { if (err) console.warn(err.message); }); }; 

我知道人们在讨论关于池的问题,但是当我将池中的mongo连接与所有请求的单个连接进行基准比较时,单个连接实际上performance更好。 当然,这大概是一年前的事,但是我怀疑这个基本概念已经改变了。 所有的请求都是asynchronous的,所以不需要多个连接来完成同时请求。

至于MongoClient,我想这是他们鼓励的新语法。 无论哪种方式,它本质上是一个客户端对象,无论使用哪种风格,您都希望保持并访问它。

从你最后的代码片段,看起来像你使用Express或类似的框架。 您可以使用express-mongo-db来获取req对象中的连接。 这个中间件会为你caching连接,并与其他传入的请求分享:

 app.use(require('express-mongo-db')(require('mongodb'), { db: 'test' })) app.post('/employee', function(req, res){ // req.db.collection('names'),insert(req.name) // Put req.name in database }); app.post('/car', function(req, res){ // req.db.collection('names').insert(req.name) // Put req.car in database });