realguess
realguess

Reputation: 1151

How to close all connections to the MongoDB server

I am using Node MongoDB native driver to connect to MongoDB database:

// Open a connection
db.open(function (err, db) {
  db.close();
});

// Open another connection
db.open(function (err, db) {
  db.close();
});

I saw two connection accepted in mongodb.log file, but only one end connection. And the program did not exit, I think it's still waiting for the second connection to be closed. How do you close all connections?

Upvotes: 1

Views: 15299

Answers (1)

Eve Freeman
Eve Freeman

Reputation: 33155

You are hiding your variable db with your callback parameter.

Try this instead.

// Open a connection
db.open(function (err, p_db) {
  db.close();
}); 

// Open another connection
db.open(function (err, p_db) {
  db.close();
});

Update: Ok, I guess I was confused about the parameters in the callback, sorry. Your problem (from the gist), is because you are executing two db.opens with the same db object before you're closing them. Also, it looks like you need separate server objects unless you do things in sequence.

So, what you could do, instead, if you wanted to guarantee it in sequence, is (also, the version of mongodb I have doesn't seem to have the _serverState defined, so I changed it to connected):

console.log('[1]', db.serverConfig.connected);
db.open(function (err, db) {
  console.log('[2]', err, db.serverConfig.connected);
  db.close();
  console.log('[3]', err, db.serverConfig.connected);

  console.log('[4]', db.serverConfig.connected);
  db.open(function (err, db) {
    console.log('[5]', err, db.serverConfig.connected);
    db.close();
    console.log('[6]', err, db.serverConfig.connected);
  });
});

Which prints:

[1] false
[2] null true
[3] null false
[4] false
[5] null true
[6] null false

Alternatively, you could define two db variables--but you also need to define two server variables, or it hangs after the first one closes. Like so:

var mongodb  = require('mongodb')
  , server   = new mongodb.Server('localhost', 27017, {})
  , server2   = new mongodb.Server('localhost', 27017, {})
  , db       = new mongodb.Db('test', server, {})
  , db2       = new mongodb.Db('test', server2, {})
  ;

console.log('[1]', db.serverConfig.connected);
db.open(function (err, db) {
  console.log('[2]', err, db.serverConfig.connected);
  db.close();
  console.log('[3]', err, db.serverConfig.connected);
});

console.log('[4]', db2.serverConfig.connected);
db2.open(function (err, db2) {
  console.log('[5]', err, db2.serverConfig.connected);
  db2.close();
  console.log('[6]', err, db2.serverConfig.connected);
});

Which prints (for me, and I guess you can't count on the order of 1,4,2,3...):

[1] false
[4] false
[2] null true
[3] null false
[5] null true
[6] null false

Upvotes: 2

Related Questions