2016-06-01 6 views
0

안녕하세요, 저는 모듈을 만드는 데 새로운 경험이 있습니다. 주 응용 프로그램에서 내 mongodb 연결 풀에 액세스하는 데 약간의 문제가 있습니다. 내가 mongo-pool.js 필요하고 그것은 성공적으로 연결 몽고 말한다 mongoPool.start()를 호출 할 때 DB 개체가 쿼리를 만들기 위해 액세스 할 수없는 있지만,MongoDB | Module.exports가있는 Node.js 연결 풀링

// mongo-pool.js 
// ------------- 

var assert = require('assert'); 
var mongodb = require('mongodb'); 
var MongoClient = mongodb.MongoClient; 
var url = 'connection_url'; 

var mongoPool = { 
    start: function() { 
     MongoClient.connect(url, function(err, db) { 
      assert.equal(null, err); 
      console.log("Successfully connected to mongo"); 

      // Make the db object accessible here? 

     }); 
    } 

} 

module.exports = mongoPool; 

:

다음은 모듈이다. 기본 js 파일은 다음과 같습니다.

var mongoPool = require('./mongo-pool.js'); 
var pool = mongoPool.start(); 


var collection = pool.db.collection('accounts'); 
collection.update(
    { _id: 'DiyNaiis' }, 
    { $push: { children: 'JULIAN' } } 
) 

변수 풀이 정의되지 않았습니다. 나는 이유를 알아낼 수 없다. 모듈에서 return db을 시도했지만 작동하지 않았다.

도움을 주시면 감사하겠습니다. 감사합니다.

답변

0

내 친구가 문제의 원인을 파악하는 데 도움을주었습니다. 여기에 누구나 들어갈 수있는 해결책이 있습니다.

나는 자신을 내 mongo-pool.js 모듈을 업데이트하고, DB 속성을 할당 :

var assert = require('assert'); 
var mongodb = require('mongodb'); 
var MongoClient = mongodb.MongoClient; 
var url = 'my_database_url'; 

var mongoPool = { 
start: function() { 
    MongoClient.connect(url, function(err, db) { 
     assert.equal(null, err); 

     var self = this; 
     self.db = db; 
     // THESE ASSIGNMENTS 

     console.log("Successfully connected to mongo"); 

     // Make the db object accessible here? 

    }); 
} 

} 

module.exports = mongoPool; 

그럼 내 main.js 파일 :

var mongoPool = require('./mongo-pool.js'); 
// Include My mongo global module 

new mongoPool.start(); 
// Initialize the new MongoDB object globally 

setTimeout(function() { 
    console.log(db); 
}, 3000); 
// Set a 3 second timeout before testing the db object... 
// It will return undefined if it's called before the mongo connection is made 

이제 db 객체는 모듈에서 전 세계적으로 사용할 수 있습니다.