I am successfully connecting to Mongo in my index.js file. From there I am trying to set the client to a variable and export it to another module. I have tried 3 ways and I am not wrapping my head around how to get the resolved promise exported for use in another module where my data access methods are that my controller uses.
Method 1. An async function and then function call.
index.js
const port = process.env.PORT || 8000
const uri = process.env.COOKIE_DB_URI
const client = new MongoClient(uri, {
useNewUrlParser: true,
poolSize: 50,
useUnifiedTopology: true,
})
let db = null
async function connectToMongoDB() {
try {
await client.connect()
await listDatabases(client) // just a local function to console databases
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)
I want to set db = client.connect() resolved promise, I wasn’t able to get it to work
Method 2. Mongo connect with callback
MongoClient.connect(
uri,
{
useNewUrlParser: true,
poolSize: 50,
useUnifiedTopology: true,
},
function (err, database) {
if (err) {
console.error(err.stack)
process.exit(1)
}
console.log(
'line 72 index.js',
database.db('cookieBiz').collection('orders') // can see db
)
listDatabases(database)
OrdersDAO.injectDB(database)
db = database // doesn't work
}
)
export default db
According to the docs, “callback will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured.” So if the callback is executed after the Mongo.connect(), is the promise resolved by the time the callback is executed? If so why can I not set db variable to database param and then export it?
Method 3 is similar to above except I use a then()
MongoClient.connect(
uri,
{
useNewUrlParser: true,
poolSize: 50,
useUnifiedTopology: true,
})
.then(async (client) => {
listDatabases(client)
await OrdersDAO.injectDB(client)
db = client // doesn't work
app.listen(port, () => {
console.log(`listening on port ${port}`)
})
})
.catch((err) => {
console.error(err.stack)
process.exit(1)
})
export default db
And in my OrdersDAO.js, similar to M220js course
import db from '../index.js'
static async getOrders() {
try {
// how do I get into the collection here? to get database and collection
console.log(
'OrdersDAO.getOrders ~~~ made it to the OrdersDAO step 2',
db // nope, still not available!
)
} catch (e) {
console.error(`OrdersDAO ~~~ Unable to get orders: ${e}`)
return { e }
}
}
So with all three versions I am still not sure how to be able to use this connection in another file with a simple export? My understanding is that the connection is opened and the pool is used to so that there is not a constant opening and closing of connections hitting, in my case Atlas. I looked here, StackOverflow, the docs, docs, and I tried emulating the pattern from M200js in Mongo University. I am getting confused and moving in circles.