It seems that I can't close a MongoDB connection with Node.js native driver. When I run node replica.js the script never ends, hence the connection can't be closed for some reason.
Here is the code. It's a replica set but I don't think that it's a problem:
var mongodb = require('mongodb')
, Db = mongodb.Db
, Server = mongodb.Server
, ReplSet = mongodb.ReplSet;
// Replica set
var replSet = new ReplSet( [
new Server('localhost', 27017), // Primary
new Server('localhost', 27018), // Secondary
new Server('localhost', 27016), // Secondary
],
{ rs_name: 'replica', read_secondary: true }
);
var db = new Db('test', replSet, { native_parser: true, w: 1 });
// Opening
db.open(function (err, db) {
if (err) console.error(err);
db.close();
});
Connecting to a single mongod instance works just fine, connection get closed and the script ends, without the need (suggested by robertklep) of process.exit() call:
var mongodb = require('mongodb')
, Db = mongodb.Db
, Server = mongodb.Server;
// Single instance
var server = new Server('localhost', 27017):
var db = new Db('test', server, { native_parser: true, w: 1 });
// Opening
db.open(function (err, db) {
if (err) console.error(err);
db.close();
});
It turns out that it was a bug, now fixed in 1.3.6. Look at this issue I opened few days ago. The funny thing is that it's my first time with MongoDB...
You may need to force the pool of connections to close in this case by passing true as the first parameter to close. You should also provide a callback so that you can be alerted to any problems when trying to close:
db.open(function (err, db) {
if (err) console.error(err);
db.close(true, function (err) {
if (err) console.error(err);
else console.log("close complete");
});
});