2012-08-07 2 views
5

다음은 약간의 이야기입니다.node-mongodb- 네이티브, 콜백, 스코프 및 TypeError

옛날 옛적에 약간의 프로젝트가 node-mongodb-native을 사용하려고했습니다. 그러나 매우 수줍음이 많았고 래퍼 객체를 사용하여 숨기고 싶었습니다.

var mongodb = require('mongodb'), 
    Server = mongodb.Server, 
    Db = mongodb.Db, 
    database; 

var MongoModule = {}; 

MongoModule.setup = function() { 
    // Create a mongodb client object 
    var client = new Db(this.config.databaseName, 
     new Server(
      this.config.serverConfig.address, 
      this.config.serverConfig.port, 
      this.config.serverConfig.options 
     ), 
     this.config.options 
    ); 

    // Open the connection! 
    client.open(function(err, db) { 
     if (err) throw err; 
     database = db; 
     console.log('Database driver loaded.'); 
    }); 
}; 

setup 방법은 작은 프로젝트를 시작하는 방법이었다. 응용 프로그램이 실행 중일 때 호출되고있었습니다.

작은 프로젝트에서 collection 메서드의 래퍼 메서드를 node-mongodb-native으로 추가했습니다.

MongoModule.collection = function() { 
    database.collection.apply(this, arguments); 
}; 

하지만 작은 프로젝트는이 방법이 작동하지 않는다는 것을 알아 냈습니다. 왜 그런지 이해하지 못했습니다!

// In the client.open callback: 
db.collection('pages', function(e, p) { 
    // no error, works fine 
}); 

// in the same callback: 
MongoModule.collection('pages', function(e, p) { 
    // error :(
}); 

작은 프로젝트가 관련 있다고 생각하지 않지만 오류는 다음과 같았습니다. 그의 가장 친한 친구 인 Google은 유용한 결과를 얻지 못했지만 기존의 수정 된 버그를 나타 냈습니다.

TypeError: Cannot read property 'readPreference' of undefined 
    at new Collection (/home/vagrant/tartempion/node_modules/mongodb/lib/mongodb/collection.js:56:92) 
    at Object.Db.collection (/home/vagrant/tartempion/node_modules/mongodb/lib/mongodb/db.js:451:24) 
    at Object.MongoModule.collection (/home/vagrant/tartempion/core/databases/mongodb.js:27:25) 
    at proxy [as collection] (/home/vagrant/tartempion/node_modules/ncore/lib/core.js:116:51) 
    at Object.module.exports.getIndex (/home/vagrant/tartempion/pies/page/model.js:4:17) 
    at proxy [as getIndex] (/home/vagrant/tartempion/node_modules/ncore/lib/core.js:116:51) 
    at Object.module.exports.index (/home/vagrant/tartempion/pies/page/controller.js:7:20) 
    at callbacks (/home/vagrant/tartempion/node_modules/express/lib/router/index.js:272:11) 
    at param (/home/vagrant/tartempion/node_modules/express/lib/router/index.js:246:11) 
    at pass (/home/vagrant/tartempion/node_modules/express/lib/router/index.js:253:5) 

PS : 당신은 실패 파일, here is a gist을 원하는 경우.

답변

3

당신은 database 개체의 컨텍스트가 아닌 MongoModule 객체의 방법 collection을 적용해야합니다

database.collection.apply(database, arguments); 
+0

와우. 어떻게 내가 어리석은 짓일 수 있겠 어. 감사! –

+0

이런 종류의 것을 간과하는 것은 너무 쉽습니다. – scttnlsn