Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close MongoDB connections properly in Node.js?

The following code is "working", in that it returns the document in the console:

var Db = require('mongodb').Db;
var mongoUri = 'mongodb://localhost:27017/basketball';

exports.games = function(req, res){
    console.log(req);
    res.end("list of games");
    Db.connect(mongoUri, function(err, db) {
        console.log('connected!');
        db.collection('game_ids', function(err, coll) {
            coll.findOne({'date' : '2012-12-07'}, function(err, doc) {
                console.log(doc);
            });
        });
        db.close();
    });
};

>
connected!
{ _id: 50b01b31597f14213a00010f,
  date: '2012-12-07',
  espn_id: '400277990',
  hid: '20',
  aid: '2',
  home: '76ers',
  away: 'Celtics',
  season: '2013',
  during: 'regular',
  scrape: null }

But when I look at the mongod console, I see that every time I refresh the page, it seems to open more and more connections without closing them. Here you can see after 5 refreshes, I now have 25 open connections apparently (you have to scroll to the right to see the numbers):

Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57587 #121 (21 connections now open)
Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57588 #122 (22 connections now open)
Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57589 #123 (23 connections now open)
Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57590 #124 (24 connections now open)
Sat Dec  8 12:29:32 [initandlisten] connection accepted from 127.0.0.1:57591 #125 (25 connections now open)

What am I doing wrong?

like image 267
Evan Zamir Avatar asked Dec 08 '12 20:12

Evan Zamir


1 Answers

You're attempting to close the connection while the work is being done.

    // the work is done in the call back functions
    db.collection('game_ids', function(err, coll) {
        coll.findOne({'date' : '2012-12-07'}, function(err, doc) {
            console.log(doc);
        });
    });

    // the work above with the callback is async, this executes
    // immediately after initiating that work.
    db.close();

If you're going to open and close in every call, you would close after the work is done (after the console.log call in your case).

You may also want to look into connection pooling so you don't have to open/close on every call. More here:

http://technosophos.com/content/nodejs-connection-pools-and-mongodb

You should also do error checking by checking the err in the callback functions. for example, if getting the collection failed, the findOne shouldn't be done etc...

like image 88
bryanmac Avatar answered Oct 05 '22 23:10

bryanmac