node-mongodb-native,callback,范围和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方法是一个小项目开始的方法。 它在应用程序运行时被调用。

为了尝试一下,小项目为node-mongodb-nativecollection方法添加了一个包装方法。

 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:如果你想要一个失败的文件, 这是一个要点 。

您需要将方法collection应用于database对象而不是MongoModule对象的上下文中:

 database.collection.apply( database, arguments );