2012-12-08 1 views
0

:Node.js에서 MongoDB 연결을 올바르게 종료하는 방법은 무엇입니까? 이 콘솔에서 문서 반환에 다음의 코드는, "작업"입니다

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 콘솔에서 볼 때, 나는이 페이지를 새로 고침 할 때마다, 열 보인다 참조 점점 더 많은 연결을 닫지 않고 다음은 지금 분명히 25 개 열려있는 연결을, 5 새로 고침 후 볼 수있다 (당신은 번호를 확인하기 위해 오른쪽으로 스크롤해야) : 내가 잘못 뭐하는 거지

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) 

?

답변

5

작업이 완료되는 동안 연결을 닫으려고합니다.

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

또한 오류가 콜백 함수에서 ERR을 확인하여 확인해야한다. 예를 들어 컬렉션을 가져 오지 못하면 findOne을 수행해서는 안됩니다.

+0

Thanks! 그건 의미가 있습니다. 나는 아직 노드와 비동기 적이 지 않은 것 같아. :) –

관련 문제