Reputation: 2531
I have this code in db.js:
const mongoClient = require('mongodb').MongoClient;
const dotenv = require("dotenv");
dotenv.config();
const mongoDbUrl = process.env.CONNECTIONSTRING;
mongoClient.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
module.exports = db;
});
then I want to add it in the file User.js with
const mydb = require("../db");
console.log(mydb);
, but i get an empty object:
{}
What's the correct code to make the User.js receive mydb?
BTW, console logging db in db.js returns what i need.
Upvotes: 0
Views: 241
Reputation: 13675
Requiring is synchronous while the connection is asynchronous. It will eventually be there but what you should do is export an object which has an asynchronous init function then call that during startup to ensure that the rest of your running code happens after that. Essentially you should not "run" any code in the module but only export values.
// db.js
const mongoClient = require('mongodb').MongoClient;
const dotenv = require("dotenv");
class Db {
async init() {
dotenv.config();
const mongoDbUrl = process.env.CONNECTIONSTRING;
this.db = await mongoClient.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true }
}
}
module.exports = new Db()
Then in your calling code:
// main.js
const db = require('./db')
const app = require('./app')
async function main() {
await db.init()
await app.run()
}
main().then(() => console.log('done.')).catch(console.error)
Upvotes: 1