【问题标题】:node-mongodb-native, callback, scope and TypeErrornode-mongodb-native、回调、范围和 TypeError
【发布时间】:2012-08-07 19:30:44
【问题描述】:

这是一个小故事。

曾几何时,一个小项目想使用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 :(
});

错误如下,即使这个小项目认为它不相关。他最好的朋友 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

【问题讨论】:

    标签: javascript node.js mongodb node-mongodb-native


    【解决方案1】:

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

    database.collection.apply( database, arguments );
    

    【讨论】:

    • 这种事情很容易被忽视。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多