我是Node.js和MongoDB的新手,但我已经设法将SO和mongo的文档放在一起。
Mongo documentetion给出了一个例子:
// 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");
}
});
如果我只需要在一个地方的一个功能中使用DB,那么看起来很好。搜索和阅读SO告诉我,我不应该每次都打开一个新连接,而是使用一个池并重用我第一次获得的数据库对象。这个答案在SO上很丰富,但我不知道如何首先获得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 reuse MongoDB reference中发现了一个类似的问题,但从这个(http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html)的外观来看,我看起来应该使用MongoClient而不是db()。而且我不确定它是否解决了我的问题......
答案 0 :(得分:36)
您总是可以编写一个初始化数据库连接的模块,并在整个程序中访问它们。例如:
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连接和单个连接进行基准测试时,单个连接实际上表现得更好。当然,这是大约一年前,但我怀疑基本概念已经改变。所有请求都是异步的,因此不需要多个连接来同时发出请求。
就MongoClient而言,我猜这是他们鼓励的新语法。无论哪种方式,它本质上都是一个客户端对象,无论您使用哪种样式,都要保留并使其可访问。
答案 1 :(得分:3)
从上一个代码段开始,您似乎使用了Express或类似的框架。您可以使用express-mongo-db获取req
对象内的连接。此中间件将为您缓存连接并与其他传入请求共享:
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
});