首页 > 解决方案 > MongoDB客户端(nodejs)不关闭连接

问题描述

我有以下代码,该函数被调用数百万次以获取 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 并检查有多个 TCP 连接到我的 mongodb 数据库,这些连接没有被关闭,为什么会这样?

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

标签: node.jsmongodbtcpconnection

解决方案


推荐阅读