Skip to content

Commit

Permalink
fix minor bug: ensure single database connection on server startup (#…
Browse files Browse the repository at this point in the history
…2240)

* Fix MongoDB URI in loadPlugin function

* Implement connection check before establishing new database connection

* Replace isConnected variable with mongoose.connection.readyState check

* Add check comments to db.ts file
  • Loading branch information
lokeshwar777 authored Apr 22, 2024
1 parent ff67081 commit 3f59503
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/config/plugins/loadPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mongoose from "mongoose";
// Only loads plugin data for the time if it's not currently present in the database
const loadPlugins = async (): Promise<void> => {
try {
await mongoose.connect(process.env.MONGO_URI as string);
await mongoose.connect(process.env.MONGO_DB_URL as string);
logger.info("\x1b[1m\x1b[32m%s\x1b[0m", `Connected to the database`);
const res = await Plugin.find();
const databaseTitle = mongoose.connection.db.databaseName;
Expand Down
10 changes: 10 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import { checkReplicaSet } from "./utilities/checkReplicaSet";
let session!: mongoose.ClientSession;

export const connect = async (dbName?: string): Promise<void> => {
// firstly we check if a connection to the database already exists.
if (mongoose.connection.readyState !== 0) {
// if the connection state is not 0, it means a connection already exists so we return.
return;
}
// if no connection exists, we try to establish a new connection.
try {
await mongoose.connect(MONGO_DB_URL as string, {
dbName,
Expand Down Expand Up @@ -52,6 +58,10 @@ export const connect = async (dbName?: string): Promise<void> => {
};

export const disconnect = async (): Promise<void> => {
if (mongoose.connection.readyState === 0) {
logger.warn("No active database connection to disconnect.");
return;
}
session?.endSession();
await mongoose.connection.close();
};
Expand Down

0 comments on commit 3f59503

Please sign in to comment.