2012-08-07 84 views
5

这是一个小故事。node-mongodb-native,回调,范围和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方法添加了包装方法。

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 :(
}); 

错误是以下,即使小项目不认为它是相关的。他最好的朋友谷歌没有提供任何有用的结果,而是一个旧的固定错误。

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

您需要应用该方法collectiondatabase对象的上下文,而不是MongoModule对象:

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

哇。我怎么会这么愚蠢。谢谢! – 2012-08-07 19:51:00

+0

很容易忽略这种事情。 – scttnlsn 2012-08-07 19:53:06