I have a separate js file that exports the mongoDB connection so the other files can use it without creating a new connection. (one of mongoDB's best practices)
mongoClient.js (returns the connected client)
// Defining the MongoClient
const { MongoClient } = require("mongodb");
const mongo = new MongoClient(
process.env.MONGO_AUTH,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
mongo.connect((err, result) => {
// result == mongo ✅
module.exports = result;
console.log(module.exports); // When the script is run alone, it works. When it's required somewhere else, nothing is logged (is it executed?)
process.on("SIGINT", function () {
mongo.close();
});
});
As written above, module.exports
seems to work. When I require it in another file, there is no export found:
in other files
const mongo = require("../mongoClient");
console.log(mongo); // {}
I've heard about something called cyclic dependencies. It seems to correspond with my case, with one difference... there is none. mongoClient.js
's only dependency is the mongodb
node_module (which, besides, is nowhere else in the other files). Then, where is the mistake, and how could I solve it?