如何在Node.js中正确关闭MongoDB连接?

时间:2012-12-08 20:33:43

标签: node.js mongodb

以下代码为“working”,因为它在控制台中返回文档:

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 }

但是当我看到mongod控制台时,我发现每次刷新页面时,似乎都会打开越来越多的连接而不关闭它们。在5次刷新后你可以看到,我现在有25个打开的连接显然(你必须向右滚动才能看到数字):

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)

我做错了什么?

1 个答案:

答案 0 :(得分:7)

您正在尝试在工作完成时关闭连接。

    // 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();

如果您打算在每次通话中打开和关闭,您将在完成工作后关闭(在您的情况下调用console.log之后)。

您可能还想查看连接池,这样您就不必在每次通话时打开/关闭。更多信息:

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

您还应该通过检查回调函数中的错误来进行错误检查。例如,如果收集失败,则不应该执行findOne等...