繁体   English   中英

如何正确使用module.exports?

[英]How to use module.exports correctly?

我有一个带有 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

我在这里做错了什么? 请帮忙!

我在 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 
...
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM