Javascript 节点mongodb本机、回调、作用域和类型错误

Javascript 节点mongodb本机、回调、作用域和类型错误,javascript,node.js,mongodb,node-mongodb-native,Javascript,Node.js,Mongodb,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

这里有一个小故事

从前,有一个小项目想要使用。然而,它非常害羞,它想使用包装器对象隐藏在它后面

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
方法是启动小项目的一种方法。应用程序运行时正在调用它

为了尝试一下,这个小项目为
节点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 :(
});
错误如下,尽管这个小项目认为它与此无关。他最好的朋友谷歌没有发现任何有用的结果,只是发现了一个旧的错误

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:如果您想要一个失败的文件,.

您需要在
数据库
对象的上下文中应用方法
集合
,而不是
MongoModule
对象:

database.collection.apply( database, arguments );

这种事情很容易被忽视。