Multiple node-mongodb-native connections

2019-03-01 18:19发布

问题:

When I run this Node.js code:

var mongodb = require('mongodb'),
  MongoClient = mongodb.MongoClient;
MongoClient.connect('mongodb://localhost:27017/mydb', function(error, db) {
  if (error) {
    throw (error);
  }
  console.log('Connected!');
});

The mongo logs show 5 connections open:

sudo mongod
mongod --help for help and startup options
2014-11-04T21:03:23.107-0700 [initandlisten] MongoDB starting : pid=27572 port=27017 dbpath=/data/db 64-bit host=mylaptop
2014-11-04T21:03:23.107-0700 [initandlisten] db version v2.6.2
2014-11-04T21:03:23.107-0700 [initandlisten] git version: nogitversion
2014-11-04T21:03:23.107-0700 [initandlisten] build info: Darwin minimountain.local 12.5.0 Darwin Kernel Version 12.5.0: Sun Sep 29 13:33:47 PDT 2013; root:xnu-2050.48.12~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
2014-11-04T21:03:23.107-0700 [initandlisten] allocator: tcmalloc
2014-11-04T21:03:23.107-0700 [initandlisten] options: {}
2014-11-04T21:03:23.110-0700 [initandlisten] journal dir=/data/db/journal
2014-11-04T21:03:23.110-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-11-04T21:03:23.136-0700 [initandlisten] waiting for connections on port 27017
2014-11-04T21:03:28.315-0700 [initandlisten] connection accepted from 127.0.0.1:61163 #1 (1 connection now open)
2014-11-04T21:03:28.323-0700 [conn1] end connection 127.0.0.1:61163 (0 connections now open)
2014-11-04T21:03:28.326-0700 [initandlisten] connection accepted from 127.0.0.1:61164 #2 (1 connection now open)
2014-11-04T21:03:28.326-0700 [initandlisten] connection accepted from 127.0.0.1:61165 #3 (2 connections now open)
2014-11-04T21:03:28.327-0700 [initandlisten] connection accepted from 127.0.0.1:61166 #4 (3 connections now open)
2014-11-04T21:03:28.328-0700 [initandlisten] connection accepted from 127.0.0.1:61167 #5 (4 connections now open)
2014-11-04T21:03:28.328-0700 [initandlisten] connection accepted from 127.0.0.1:61168 #6 (5 connections now open)

Does this seem right?

回答1:

Sure. MongoClient uses the connection pools option from the node native driver. This is actually really a Server Object and the number of connections is 5 by default.

You can override the setting like this:

var async = require('async'),
    mongo = require('mongo'),
    MongoClient = mongo.MongoClient;


MongoClient.connect('mongodb://localhost/test',{ server: { poolSize: 1  }},function(err,db) {


});

So setting "poolSize" in the server options specifies the number of connections used in the pool. Best to stick with the default or higher really though.