I'm trying to reuse my MongoClient connection in another module and the export is coming up as null upon import.
index.js
import app from './server.js'
import pkg from 'mongodb'
const { MongoClient } = pkg
let db = null
async function listDatabases(client) {
try {
const dbList = await client.db().admin().listDatabases()
console.log('Databases:')
dbList.databases.forEach((db) => {
console.log(` - ${db.name}`) // I see the databases here
})
} catch (error) {
console.error(error)
}
}
MongoClient.connect(uri, {
useNewUrlParser: true,
poolSize: 50,
useUnifiedTopology: true,
})
.then(async (client) => {
listDatabases(client) // I see the databases here
db = client
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
.catch((err) => {
console.error(err.stack)
process.exit(1)
})
export default db
and then in OrdersDAO.js, I'm importing db to be able to access the db and collection. I referred to this StackOverflow
import db from '../index.js'
static async getOrders() {
try {
// db is null here
console.log('OrdersDAO.getOrders ~~~ made it to the OrdersDAO step 2', db)
} catch (e) {
console.error(`OrdersDAO ~~~ Unable to get orders: ${e}`)
return { e }
}
}
What am I doing wrong?
Below was my original async function and subsequent function call: index.js
const client = new MongoClient(uri, {
useNewUrlParser: true,
poolSize: 50,
useUnifiedTopology: true,
})
async function connectToMongoDB() {
try {
await listDatabases(client)
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
} catch (e) {
console.error(`Index.js ~~~ Unable to get database.collection: ${e}`)
} finally {
console.log('Mongo Connection is closing ~~~~')
await client.close()
}
}
connectToMongoDB().catch(console.error)