18

我是 nodejs 和 mongdb 的新手,我将在我的一个项目中使用它们,一旦我的 db 连接正常工作,我很震惊地看到我的代码确实有多少数据库连接。所以,给定这个简单的代码段:

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 建立如此多的连接才能获得单个数据库处理程序,或者我实现这个的方式有什么问题?我真的希望在那里只看到一个打开的连接......

4

2 回答 2

20

Db.connect默认情况下打开一个包含 5 个连接的池。如果您想将其限制为单个连接,您可以通过以下server选项执行此操作:

mongo.Db.connect(
    'mongodb://localhost:27017/testDB', 
    {server: {poolSize: 1}}, 
    function(err, db) { ...
于 2013-01-29T23:19:48.130 回答
0

你也可以这样通过

var mongoclient = new mongodb.MongoClient(new mongodb.Server(
    'localhost', 27017, {'native_parser': true, 'poolSize': 1} 
));
于 2013-08-15T21:03:44.743 回答