2012-08-07 12 views
5

Oto krótka historia.node-mongodb-native, callback, scope i TypeError

Dawno, dawno temu mały projekt chciał użyć node-mongodb-native. Jednak był bardzo nieśmiały i chciał użyć ukrytego obiektu do ukrycia się za nim.

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.'); 
    }); 
}; 

Metoda była sposobem na rozpoczęcie małego projektu. Został wywołany, gdy aplikacja była uruchomiona.

Aby trochę się wypróbować, mały projekt dodał metodę otoki dla metody collection z node-mongodb-native.

MongoModule.collection = function() { 
    database.collection.apply(this, arguments); 
}; 

Ale wtedy mały projekt dowiedział się, że ta metoda nie działa. Nie rozumiem, dlaczego!

// 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 :(
}); 

Błąd był następujący, mimo że mały projekt nie uważa tego za powiązany. Jego najlepszy przyjaciel Google nie przyniósł żadnego pożytecznego wyniku, ale stary naprawiony błąd.

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: jeśli chcesz zepsuty plik here is a gist.

Odpowiedz

3

trzeba zastosować metodę collection w kontekście obiektu database zamiast obiektu MongoModule:

database.collection.apply(database, arguments); 
+0

Wow. Jak mogłem być tak głupi. Dzięki! –

+0

Łatwo jest przeoczyć tego rodzaju rzeczy. – scttnlsn