首页 > 解决方案 > 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 并忘记关闭

标签: node.jsmongodb

解决方案


推荐阅读