0

I have the following code, this functions is called millions of times to get a specific field of a product in the mongo database:

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);
    }
}

Now running my nodejs app on pm2 I notice that the active handles keep increasing without decreasing, I ran the following command:

lsof -i -n -P and checked there is multiple TCP connections to my mongodb databases which are not being closed, why is this happening?

Does anyone have any clue? Thanks!

TiagoM
  • 3,458
  • 4
  • 42
  • 83
  • Take a look at https://stackoverflow.com/questions/10656574/how-do-i-manage-mongodb-connections-in-a-node-js-web-application It's old but little changed in regards of how the driver handle connection pool. – Alex Blex Jun 03 '19 at 13:14
  • In addition to Alex's comment: https://stackoverflow.com/questions/38485575/best-way-to-connect-to-mongodb-using-node-js/38493142#38493142 – kevinadi Jun 04 '19 at 01:59

0 Answers0