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方法は、小さなプロジェクトを開始するための方法でした。アプリケーションの実行中に呼び出されていました。

少し試してみるために、この小さなプロジェクトは のcollectionメソッドのラッパー メソッドを追加しましたnode-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 :(
});

小さなプロジェクトはそれが関連しているとは思わないにもかかわらず、エラーは次のとおりでした。彼の親友である 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: 失敗したファイルが必要な場合は、ここに要点があります。

4

1 に答える 1

3

オブジェクトではなくオブジェクトcollectionのコンテキストでメソッドを適用する必要があります。databaseMongoModule

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