0

I've been reading and searching about a good design related with mongodb driver.

Like here was said, there is no need to open/close connection, so I was trying to prevent boilerplate code using a dbLoader.js file like this (only using one database):

const { MongoClient } = require('mongodb')
const logger = require('./logger')
const configLoader = require('./configLoader')

module.exports = (async () => {
  const config = await configLoader()
  const client = await MongoClient.connect(config.db.uri)
  const db = client.db(config.db.dbName)
  logger.log('info', `Database ${config.db.dbName} loaded`)
  return db
})()

I wonder if there is some other approach that is better, and why. For example attaching it to app.locals (in express.js).

I'm not using mongoose and don't want to.

Ivan Beldad
  • 2,285
  • 2
  • 21
  • 33

1 Answers1

0

Consider using IOC containers such as https://github.com/inversify/InversifyJS or similar. For starters, you get the ability to mock the defined dependency for testing purposes (such as database connection) without hacky solutions, such as manual module mocking.

Luke Gmys
  • 137
  • 1
  • 7