简体   繁体   中英

MongoDB in node.js pattern

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM