5

这是一个小故事。

曾几何时,一个小项目想使用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方法是启动小项目的一种方法。它在应用程序运行时被调用。

为了尝试一下,这个小项目collectionnode-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:如果你想要一个失败的文件,这里是一个要点

4

1 回答 1

3

您需要在对象而不是对象collection的上下文中应用该方法:databaseMongoModule

database.collection.apply( database, arguments );
于 2012-08-07T19:47:20.253 回答