MongoDB:> 5个打开连接的单个数据库处理程序

我是nodejs和mongdb的新手,我将在我的一个项目中使用它,只要db连接工作,我就震惊地看到我的代码有多less数据库连接。 所以,给这个简单的代码片段:

var express = require('express'); var mongo = require('mongodb'); var app = express(); // Further details: // nodejs: v0.8.18 // mongod: v2.2.2 // node's mongodb driver: v1.2.10 app.get('/', function(req, res){ res.send('<h1>Ok</h1>'); }); var setUp = function() { // get a handler to the testDB Database mongo.Db.connect('mongodb://localhost:27017/testDB', function(err, db) { if (err) throw err; // create a test collection in the database db.createCollection('test', function(err, test) { if (err) throw err; // insert a dummy document into the test collection test.insert({'name':'admin', 'pass':'admin'}); app.listen(3000); console.log('App listening on port 3000'); }); }); } setUp(); 

当nodejs进程触发时,mongo守护进程输出这个日志位:

 ... connection accepted from 127.0.0.1:40963 #34 (1 connection now open) ... connection accepted from 127.0.0.1:40964 #35 (2 connections now open) ... connection accepted from 127.0.0.1:40965 #36 (3 connections now open) ... connection accepted from 127.0.0.1:40966 #37 (4 connections now open) ... connection accepted from 127.0.0.1:40967 #38 (5 connections now open) ... connection accepted from 127.0.0.1:40968 #39 (6 connections now open) ... end connection 127.0.0.1:40963 (5 connections now open) ... allocating new datafile /var/data/testDB.ns, filling with zeroes... ... 

当这个过程终止时,

 ... connection 127.0.0.1:40964 (4 connections now open) ... connection 127.0.0.1:40965 (3 connections now open) ... connection 127.0.0.1:40966 (2 connections now open) ... connection 127.0.0.1:40967 (1 connection now open) ... connection 127.0.0.1:40968 (0 connections now open) 

mongo驱动程序是否真的需要与mongodbuild立多个连接才能获得单个db处理程序,或者在执行此操作时出现了什么问题? 我真的希望在那里看到一个开放的连接…

Db.connect打开一个包含5个连接的池。 如果你想限制它到一个单一的连接,你可以通过这样的server选项来做到这一点:

 mongo.Db.connect( 'mongodb://localhost:27017/testDB', {server: {poolSize: 1}}, function(err, db) { ... 

你也可以像这样传递它

 var mongoclient = new mongodb.MongoClient(new mongodb.Server( 'localhost', 27017, {'native_parser': true, 'poolSize': 1} ));