I'm new to nodejs and mongdb, which I'll use in a project of mine, and as soon as I got the db connection working I was shocked to see how many database connections my code really does. So, given this simple snippet code:
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();
the mongo daemon outputs this bit of log when the nodejs process fires up:
... 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...
...
and this one when the process is terminated:
... 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)
Does the mongo driver really need to make that many connections to mongod in order to get a single db handler, or is there something wrong with the way I implemented this? I really expected to see just one open connection in there...
MongoDB configuration Even MongoDB itself has an option to limit the maximum number of incoming connections. It defaults to 64k.
You should have a single MongoDB deployment which multiple remote users can connect to. The mongod process is multi-threaded and supports tens of thousands of concurrent connections (subject to resource availability and workload).
It is best practice to keep the connection open between your application and the database server.
Db.connect
opens a pool of 5 connections, by default. If you want to limit it to a single connection you can do that via the server
options like this:
mongo.Db.connect(
'mongodb://localhost:27017/testDB',
{server: {poolSize: 1}},
function(err, db) { ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With