5

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

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)

我究竟做错了什么?

4

1 回答 1

9

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

    // 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 等...

于 2012-12-08T20:57:20.647 回答