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!