5
這是一個小故事。node-mongodb-native,回調,範圍和TypeError
曾幾何時,一個小項目想使用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
方法添加了包裝方法。
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:如果你想有一個失敗的文件,here is a gist。
哇。我怎麼會這麼愚蠢。謝謝! – 2012-08-07 19:51:00
很容易忽略這種事情。 – scttnlsn 2012-08-07 19:53:06