Why does MongoClient not work in my Node.js script finish?

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

Which is strange, if I run a local executable instance of mongod and connect to it, the script ends fine, but the remote connection just doesn't end.

Here is a short version of my script that still has a problem (with the url on the server on the command line). What's happening?

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

Just tried the code with driver version 1.2.7 / 1.2.8 and latest 1.2.9 against mongolab, and it works correctly. Therefore, it is more likely that this is a strange combination of the driver / os / node version that causes this. I suggest updating your node and driver to the latest version and try again.

+1
source

I suspect this is due to how you determined your closures, but I cannot rely on it.

For what it's worth, below is the approach I use and this closes 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); }); }); 

Here you can find the full example: https://github.com/hectorcorrea/mongoDbSample

+1
source

All Articles