javascript - node-mongodb-native、回调、范围和 TypeError

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

这是一个小故事。

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

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

最佳答案

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

database.collection.apply( database, arguments );

关于javascript - node-mongodb-native、回调、范围和 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11852796/

相关文章:

javascript - Angular 2 汇总 AoT 构建比普通 JiT 构建更大

javascript - 如何克隆 Angular UI 树中的节点?

尝试通过 SSL 与后端服务器通信的 Node.js 错误

node.js - 是否可以在nodejs Async( waterfall ,系列等...)中构建动态任务列表

javascript - 这个 2 行 jquery 可以缩短为 1 行吗?

javascript - 如何在 AngularJS 中动态设置页面加载的标题标签?

node.js - 无法关闭应用引擎版本。保持计费

javascript - 将数据渲染成 Angular 时遇到问题

java - 无法将带有连字符的 JSON 字段映射到 Java 对象字段

node.js - 在插入 MongoDB 之前是否需要清理用户输入(MongoDB+Node js 组合)