这是一个小故事。
曾几何时,一个小项目想用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-native
的 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 :(
});
错误如下,即使这个小项目认为它不相关。他最好的 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/