【发布时间】:2014-01-12 17:55:40
【问题描述】:
我目前有一个包含以下内容的数据库连接模块:
var mongodb = require("mongodb");
var client = mongodb.MongoClient;
client.connect('mongodb://host:port/dbname', { auto_reconnect: true },
function(err, db) {
if (err) {
console.log(err);
} else {
// export db as member of exports
module.exports.db = db;
}
}
);
然后我可以通过以下方式成功访问它:
users.js
var dbConnection = require("./db.js");
var users = dbConnection.db.collection("users");
users.find({name: 'Aaron'}).toArray(function(err, result) {
// do something
});
但是,如果我改为导出module.exports = db,即尝试将exports 对象分配给db 对象而不是使其成为导出的成员,并尝试通过@987654327 在users.js 中访问它@对象未定义,为什么?
如果是因为建立连接有延迟(不应该require() 等到模块完成其代码运行后再分配 module.exports 的值?),那么为什么这些示例都不起作用?
one.js
setTimeout(function() {
module.exports.x = {test: 'value'};
}, 500);
两个.js
var x = require("./one");
console.log(x.test);
或
one.js
setTimeout(function() {
module.exports.x = {test: 'value'};
}, 500);
两个.js
setTimeout(function() {
var x = require("./one");
console.log(x.test);
}, 1000);
运行$ node two.js 在这两种情况下都会打印undefined 而不是value。
【问题讨论】:
标签: javascript node.js mongodb express