【问题标题】:How to use module.exports correctly?如何正确使用 module.exports?
【发布时间】: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


【解决方案1】:

我在 index.js 中导出函数 GetDatabaseInstance 如下:

exports.GetDatabaseInstance = GetDatabaseInstance;

我将 index.js 文件导入到另一个文件中,如下所示:

const index =  require('../index')

然后我使用此导入从索引文件中获取数据库实例并查询它以从 MongoDB 获取我的文档:

var database = index.GetDatabaseInstance() //retrieve the database instance

if(database !== undefined)
var collection = await database.collection("YOUR_COLLECTION_NAME") //retrieve the collection

if(collection !== undefined)
collection.find({"userName" : "USER_NAME"}).toArray((err, user) => { //query the MongoDB collection 
...
})

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2020-12-04
    相关资源
    最近更新 更多