I have read through the documentation for connections and am confused about what will occur if I call mongoose.connect on every request to my express server with the same URL and options. Will the previous connection automatically be re-used if one exists or will a new one always be established?
I have disabled buffering as I am running on Vercels Serverless environment and need the retry loop as Vercel sometimes fails to connect to all 3 nodes In my cluster.
Here is my connection code, I call this with await
at the start of every request my Express server handles.
const connectDatabase = async function (retries = 5) {
while (retries) {
try {
conn = await mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
bufferCommands: false,
});
return conn;
} catch (err) {
console.warn(err);
retries -= 1;
console.warn(`Retries left: ${retries}`);
// wait 1 second
await new Promise(res => setTimeout(res, 1000));
}
}
// If we're here, we failed to connect after 5 attempts
throw new Error('Failed to connect to DB');
};