MongoDB客户端(nodejs)没有关闭连接

时间:2019-06-03 12:27:37

标签: node.js mongodb tcp connection

我有以下代码,此函数被数百万次调用,以在mongo数据库中获取产品的特定字段:

const mongo = require('mongodb').MongoClient

const defaultQueryProjection = {
    _id: 0,
    sku: 1,
    category: 1
}

let DB_SERVERS;
let username;
let password;
let database;


function anotherFunctionThatInitsTheAboveVariables(){
    ...
}


async function getCategoryBySkuArray(skus){

    let client;
    try {
        const dbFields =  [        
            "category"
        ];

        // Connect to DB
        const connectionUrl =
            `mongodb://${username}:${password}@${DB_SERVERS.join(',')}/?authSource=${database}`;
        client = await mongo.connect(connectionUrl, {
            useNewUrlParser: true,
            readPreference: 'secondaryPreferred',
            replicaSet,
            reconnectTries: 10,
            reconnectInterval: 300
        });

        let productsData;

        const db = client.db(database);

        // Query DB
        const queryProjection = {
            ...defaultQueryProjection,
            ...dbFields.reduce((projection, property) => ({ ...projection, [property]: 1}), {})
        };

        productsData = await db.collection('products')
            .find({sku: {$in: skus}}, {projection: queryProjection})
            .toArray();

        if(client){
            await client.close();
            console.log('Client closed');
        }else{
            console.log('Client did not close');
        }

        return productsData;

    } catch (error) {
        if(client){
            await client.close();
            console.log('Client closed');
        } else {
            console.log('Client not closed on exception');
        }
        console.log(error);
    }
}

现在在pm2上运行我的nodejs应用程序,我注意到活动句柄不断增加而不减少,我运行了以下命令:

lsof -i -n -P并检查到我的mongodb数据库是否存在多个未关闭的TCP连接,为什么会发生这种情况?

有人有任何线索吗? 谢谢!

0 个答案:

没有答案