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

时间:2015-05-02 05:51:26

标签: node.js mongodb node-mongodb-native

从我的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驱动程序可能维护一些连接池吗?这是我最好的猜测,否则不确定我做错了什么。

2 个答案:

答案 0 :(得分:3)

来自文档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

答案 1 :(得分:0)

这是因为Connection pool configuration

  

maxPoolSize = n:连接中的最大连接数   pool默认值为5

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

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