为什么我的 NodeJS 程序打开到 Mongo 的多个连接(使用本机驱动程序)

Why my NodeJS program opens multiple connections to Mongo (using native driver)

从我的 NodeJS 程序,我使用本机驱动程序连接到 Mongodb。我启动 mongod 并看到服务器正在等待连接。当我的程序连接时,我可以看到 5 个连接而不是一个。我不明白为什么会这样,因为我似乎没有做任何不寻常的事情。来自 mongod 的消息如下:

2015-05-02T15:35:17.635+1000 [initandlisten] waiting for connections on port 27017
2015-05-02T15:36:17.638+1000 [clientcursormon] mem (MB) res:51 virt:508
2015-05-02T15:36:17.639+1000 [clientcursormon]  mapped (incl journal view):320
2015-05-02T15:36:17.639+1000 [clientcursormon]  connections:0
2015-05-02T15:37:11.594+1000 [initandlisten] connection accepted from 127.0.0.1:52976 #1 (1 connection now open)
2015-05-02T15:37:11.615+1000 [conn1] end connection 127.0.0.1:52976 (0 connections now open)
2015-05-02T15:37:11.625+1000 [initandlisten] connection accepted from 127.0.0.1:52977 #2 (1 connection now open)
2015-05-02T15:37:11.626+1000 [initandlisten] connection accepted from 127.0.0.1:52978 #3 (2 connections now open)
2015-05-02T15:37:11.627+1000 [initandlisten] connection accepted from 127.0.0.1:52979 #4 (3 connections now open)
2015-05-02T15:37:11.628+1000 [initandlisten] connection accepted from 127.0.0.1:52980 #5 (4 connections now open)
2015-05-02T15:37:11.628+1000 [initandlisten] connection accepted from 127.0.0.1:52981 #6 (5 connections now open)

这是我的 NodeJS 代码,为了清楚起见,我删除了其中的一些部分:

MongoClient.connect(mongodb_connection_string, function (err, db) {
    var collections = {};
    collections.users = db.collection("users");
    collections.disciplines = db.collection("disciplines");
    var users = require("./models/users"),
        disciplines = require("./models/disciplines");
    users.setDb(collections);
    disciplines.setDb(collections);
    app.use(session({
        secret: 'keyboard cat',
        store: new MongoStore({
            db: db,
            ttl: 2 // in minutes
            // ttl: 14 * 24 * 60 * 60 // 14 days
        }),
        saveUninitialized: false,
        resave: true
    }));
    app.all("/*", function (req, res, next) {
        res.sendfile("index.html", {
            root: __dirname + "/public"
        });
    });
    var server = app.listen(server_port, server_ip_address, function () {});
});

当我从 mongo 控制台连接时,我只有一个连接。 Nodejs 本机 mongo 驱动程序是否可能维护一些连接池?这是我最好的猜测,否则不确定我做错了什么。

来自文档 https://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html

Connection pool configuration:
maxPoolSize=n: The maximum number of connections in the connection pool
Default value is 5

这是因为Connection pool configuration

maxPoolSize=n: The maximum number of connections in the connection pool Default value is 5

如果您想更改 maxPoolSize 值,请将其作为 connection string 中的 URL 参数传递:

var connection_string = "mongodb://localhost/mydb?maxPoolSize=50"
MongoClient.connect(connection_string, function (err, db) {