Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node program with promises doesn't finish

I cannot for the life of me figure out why this doesn't finish:

var pmongo = require('promised-mongo');
var db = pmongo('mongodb://localhost/builder');
var block_id = '538d097bbb12479d0e9f70ab';

var collection = db.collection('block');
collection.findOne({_id:db.ObjectId(block_id)})
.then(function(result) {
    console.dir(result);
}).done();

It bascially just hangs. findOne returns a promise, I'm calling done. Strangely, when I close the database (ie db.close()) in the then, it finishes.

I'm trying to eventually make this handled via express, so I don't really want to close the database. What's the trick????

like image 779
Nick Lang Avatar asked Jun 04 '14 18:06

Nick Lang


1 Answers

MongoDB connections are intended to be persistent. You create one of them (or a pool of them) and then re-use that connection throughout your application.

This persistent network connection will keep the node.js process alive, so when you want to shut down the node process, you must manually close the connection. This is a common pattern with database connections and the same thing would happen if you were connecting to MySQL.

In an express.js application, just make the connection once, at the top of your file, then re-use that connection for every request.

like image 100
ForbesLindesay Avatar answered Oct 19 '22 15:10

ForbesLindesay