【发布时间】:2020-04-03 04:04:19
【问题描述】:
我有一个带有 module.export 的 index.js 文件,如下所示:
var databaseInstance, collection;
app.listen(3000, () => {
MongoClient.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true }, (error, client) => {
if(error) {
console.log(error)
throw error;
}
databaseInstance = client.db(DATABASE_NAME);
collection = databaseInstance.collection("Users");
});
});
function GetDatabaseInstance() {
if (!databaseInstance) {
console.error("databaseInstance has not been set");
} else {
return databaseInstance;
}
}
module.exports = {
GetDatabaseInstance: function() {
return GetDatabaseInstance();
}
};
CONNECTION_URL 和 DATABASE_NAME 被硬编码为来自 MongoDB 的 Atlas 的值。我已经验证 databaseInstance 不是未定义的。
现在我希望能够在另一个文件 user-ctrl.js 中使用 databaseInstance 的值,该文件是一个控制器文件。我按如下方式导入 index.js:
const Index = require('../index.js')
我正在尝试在此文件中使用函数 GetDatabaseInstance(),以便可以访问其中的 databaseInstance 的值。我这样做如下:
var database = Index.GetDatabaseInstance()
但是我收到错误:UnhandledPromiseRejectionWarning: TypeError: Index.GetDatabaseInstance is not a function
我在这里做错了什么?请帮忙!
【问题讨论】:
-
能否请您检查此文件中此行之后是否没有任何
module.exports语句。因为如果这是 express 主文件,那么最后会有module.exports = app;。 -
可以发
index.js的全部内容吗?
标签: javascript node.js mongodb mongoose mongodb-atlas