node.js - mongodb中的关闭连接-应用程序卡住了-好吗?
问题描述
我有以下 mongo 类来处理连接
export default class MongoService {
constructor ({ config }) {
this.options = {}
this.connection = null
this.config = config
Object.assign(this.options, config.get('mongo'))
}
async closeConnection(){
this.connection.close()
}
async connect(){
if (!this.options.url) {
throw new Error('Db error')
}
return MongoClient.connect(this.options.url,{ useNewUrlParser: true })
}
async getConnection() {
if (!this.connection) {
this.connection = await this.connect()
}
return this.connection
}
async getCollection(collectionName) {
await this.getConnection()
let db = this.connection.db(this.options.dbname)
return await db.collection(collectionName)
}
我如何在其他文件中使用:
try {
var mongo = container.cradle.mongoService
let collection = await mongo.getCollection('test')
const cursor = collection.find({})
}catch(e){
throw new Error(e)
}finally {
await mongo.closeConnection()
}
我的问题
1 - 我的服务够好吗?
2-每次我要求收集时都需要用户 mongo.closeConnection吗?
如果我不使用关闭功能(我读的很好),应用程序被卡住并且没有关闭,例如我得到了响应但没有关闭它(如果需要)或者我只需要删除 finally 并忘记关闭
解决方案
推荐阅读
- python - 缓存/记忆异步上下文管理器
- r - 如何根据时间数据选择案例?
- javascript - 如何使用 javascript 更改 css 类选择器
- ios - DispatchQueue.main.async 如何存储它的块
- arrays - 将具有相同值的 JSON 组合到 JSON 数组中 - Scala
- docker - 来自 Jenkins Pipeline 的挂载卷不起作用
- linux - 如何同时重命名多个文件扩展名?
- elasticsearch - Cassandra:无法在特定键空间上实现一致性级别 QUORUM
- flutter - 当您在 Flutter 中使用/点击 TextFormField 时如何隐藏小部件?
- visual-studio-code - VSCode 扩展集成测试:在测试中打开文件夹会停止测试运行