I am creating a resp api with nodejs express and babael using escma6 my question is the following I have a module where I have the connection to the database and the configuration and another file called server where I create the server with express, but I am using the nodejs clusters, I see that when using the clusters and call the connection in the server file connects with each worker to the database, now my question is this would not generate a performance error so many connections in the database? taking into account that each time that a worker finishes it dies and another one is generated therefore also another connection to bd.
this is my server file
"use strict";
import 'dotenv/config';
import app from './app';
import cluster from 'node:cluster';
import { cpus } from 'node:os';
import process from 'node:process';
import { dbConexion } from "./db/db";
const port = process.env.PORT || 3000;
const numCPUs = cpus().length;
if (cluster.isPrimary) {
console.log(` Primary ${process.pid} is running`);
// Fork workers.
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
app.listen(port, () => {
console.log(` Worker ${process.pid} started`);
});
//db conexion
dbConexion();
}
import 'dotenv/config'
import { connect } from "mongoose";
export const dbConexion = async () =>{
const MONGO_URI = process.env.DB_URI || "db";
try{
const db = await connect(
MONGO_URI,
{
keepAlive:true,
useNewUrlParser:true,
useUnifiedTopology:true
}
);
console.log('Db connected to ',db.connection.name);
}catch(err){
console.log('Db Connection failure:',err);
}
}
i would like to know if this is correct or it can generate problems later and how i could improve it pdta: no matter where i put the connection to the db in the server file it is still called 4 times