我是nodejs和mongdb的新手,我将在我的一个项目中使用它,一旦我的数据库连接正常工作,我很震惊地看到我的代码确实有多少数据库连接。所以,给出这个简单的代码片段:
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驱动程序是否真的需要与mongod建立多个连接才能获得单个数据库处理程序,或者我实现此方法有什么问题?我真的希望在那里看到一个开放的连接...
答案 0 :(得分:20)
Db.connect
会打开一个包含5个连接的池。如果您想将其限制为单个连接,可以通过server
选项将其限制为:
mongo.Db.connect(
'mongodb://localhost:27017/testDB',
{server: {poolSize: 1}},
function(err, db) { ...
答案 1 :(得分:0)
您也可以像那样传递
var mongoclient = new mongodb.MongoClient(new mongodb.Server(
'localhost', 27017, {'native_parser': true, 'poolSize': 1}
));