Gracefully Shutdown of MongoDB Connection
Unanswered
Champagne D’Argent posted this in #help-forum
Champagne D’ArgentOP
In my prior Node Apps, I would create a singleton for the mongo connection and share a getter which provided access. That same connection setup SIGTERM, SIGINT, and SIGHUP process watchers to close it's connection on nodemon restart.
Next on dev server never seems to trigger these on save/hmr, and instead creates a new Mongo Connection every time.
I've been receiving warnings from Mongo via email about exceeding connection limits, and my terminal has started warning about process.env watcher limits related to these 3 calls after the dev server has been up and running for a minute.
Is there a better way to do this than what I have done below? None of the process 'gracefulShutdown' callbacks ever seem to run.
Next on dev server never seems to trigger these on save/hmr, and instead creates a new Mongo Connection every time.
I've been receiving warnings from Mongo via email about exceeding connection limits, and my terminal has started warning about process.env watcher limits related to these 3 calls after the dev server has been up and running for a minute.
Is there a better way to do this than what I have done below? None of the process 'gracefulShutdown' callbacks ever seem to run.
import { MongoClient } from "mongodb";
const DbConnection = function () {
let db: MongoClient;
async function DbConnect(): Promise<MongoClient> {
try {
let url = `mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@portfoliocluster.aewfysa.mongodb.net/?retryWrites=true&w=majority`;
let _db = await MongoClient.connect(url);
const gracefulShutdown = () => {
_db.close(false).then(() => {
console.log("MongoDB Connection Successfully Closed...");
process.exit(0);
});
};
process.on("SIGTERM", () => gracefulShutdown());
process.on("SIGINT", () => gracefulShutdown());
process.on("SIGHUP", () => gracefulShutdown());
return _db;
} catch {
throw new Error("Unable to connect to MongoDb URL in DbConnection.ts");
}
}
async function get(): Promise<MongoClient> {
try {
if (db != undefined) {
return db;
}
db = await DbConnect();
return db;
} catch {
throw new Error("Unable to connect to MongoDb URL in DbConnection.ts");
}
}
return {
get,
};
};
const exportable = DbConnection();
export default exportable;1 Reply
your issue sounds like Prisma one. check how they implement a singleton https://www.prisma.io/docs/guides/other/troubleshooting-orm/help-articles/nextjs-prisma-client-dev-practices