4

I have a one-shot Node script that makes some changes to a MongoDB database on MongoLab. However, once it finishes, it never exits the event loop (I always have to ctrl+C it), no matter how much db.close() and db.logout() calling I do.

What's strange is, if I start a local running instance of mongod and connect to that, the script finishes fine, but the remote connection just never ends.

Here is a short version of my script that still has the issue (taking the URL to the server on the command line). What's going on?

var mongodb = require("mongodb");

function onSuccess(cb){
  return function(err) {
    if (err) {
      console.error(err)
    } else {
      cb.apply(this,Array.prototype.slice.call(arguments,1))
    }
  }
}

console.log("Connecting to "+process.argv[2]+' ...');
mongodb.MongoClient.connect(process.argv[2],onSuccess(function(db){
  console.log("Connected.");
  db.logout(onSuccess(function(logoutResult){
    db.close(onSuccess(function(closeResult){
      console.log("All finished. Can has prompt return nao?")
    }));
  }));
}));
Stuart P. Bentley
  • 10,195
  • 10
  • 55
  • 84

2 Answers2

1

I suspect it has to do with the way you have defined your closures but I cannot quite put my finger on it.

For what is worth, below is the approach that I use and this does close the connection as expected:

MongoClient.connect(dbUrl, function(err, db) {

  if(err) return callback(err);

  var collection = db.collection(dbCollection);
  collection.find().toArray(function(err, items){

    db.close()
    if(err) return callback(err);
    callback(null, items);

  });

});

You can find a full example here: https://github.com/hectorcorrea/mongoDbSample

Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • No, it's not that- I just tested and my script does work, for local connections, and your script has the same problem, for remote connections. – Stuart P. Bentley Dec 21 '12 at 16:07
1

Just tried the code with driver version 1.2.7/1.2.8 and the newest 1.2.9 against mongolab and it works correctly. So more likely its a weird combination of driver/os/node version that's causing this. I suggest upgrade your node and driver to the latest version and try again.

christkv
  • 4,370
  • 23
  • 21