简体   繁体   English

Node.js模式中的MongoDB

[英]MongoDB in node.js pattern

I've been reading and searching about a good design related with mongodb driver. 我一直在阅读和搜索与mongodb驱动程序相关的良好设计。

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): 就像这里所说的那样, 不需要打开/关闭连接 ,因此我试图使用这样的dbLoader.js文件(仅使用一个数据库)来防止样板代码:

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). 例如,将其附加到app.locals(在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. 考虑使用IOC容器,例如https://github.com/inversify/InversifyJS或类似容器。 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. 对于初学者,您可以模拟用于测试目的(例如数据库连接)的已定义依赖关系,而无需使用笨拙的解决方案(例如手动模块模拟)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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