Can't close a MongoDB connection with Node.js?

I can't seem to close the MongoDB connection with the native Node.js driver. When I run node replica.js , the script never ends, so for some reason the connection cannot be closed.

Here is the code. This is a set of replicas, but I don't think this is 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 one instance of mongod works fine, the connection closes, and the script ends without the need (suggested by robertklep) to call process.exit() :

 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(); }); 
+7
source share
2 answers

It turns out that it was a mistake, now fixed in 1.3.6. Check out this issue I discovered a few days ago. The funny thing is that this is my first time with MongoDB ...

+5
source

In this case, you may need to close the connection pool by passing true as the first close parameter. You should also provide a callback so that you can be warned of 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"); }); }); 
0
source

All Articles