alexcdev1 6 months ago
parent
commit
1cfb7c411c
1 changed files with 38 additions and 14 deletions
  1. 38 14
      src/app/lib/dbConnect.js

+ 38 - 14
src/app/lib/dbConnect.js

@@ -1,11 +1,8 @@
-// dbConnect.js
 import mongoose from "mongoose";
 
 const MONGODB_URI = process.env.MONGODB_URI;
 const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase";
 
-console.log("DB_NAME", DB_NAME, MONGODB_URI);
-
 if (!MONGODB_URI) {
   throw new Error(
     "Please define the MONGODB_URI environment variable inside .env.local"
@@ -19,24 +16,28 @@ if (!cached) {
 }
 
 async function dbConnect() {
-  console.log(666);
-
   if (cached.conn) {
     console.log("Using cached database connection");
     return cached.conn;
   }
 
-  console.log(777);
-
   if (!cached.promise) {
-    console.log(888);
-
     const opts = {
       bufferCommands: false,
       dbName: DB_NAME,
+      useNewUrlParser: true,
+      useUnifiedTopology: true,
+      connectTimeoutMS: 30000,
+      socketTimeoutMS: 30000,
+      serverSelectionTimeoutMS: 30000,
     };
 
     console.log("Attempting to connect to MongoDB...");
+    console.log(`Database Name: ${DB_NAME}`);
+    console.log(
+      `MongoDB URI: ${MONGODB_URI.replace(/\/\/(.*)@/, "//****:****@")}`
+    ); // Hide credentials in logs
+
     cached.promise = mongoose
       .connect(MONGODB_URI, opts)
       .then((mongoose) => {
@@ -44,22 +45,45 @@ async function dbConnect() {
         return mongoose;
       })
       .catch((error) => {
-        console.error("Error connecting to MongoDB:", error);
+        console.error("Error connecting to MongoDB:");
+        console.error(error);
+        if (error.name === "MongoServerSelectionError") {
+          console.error(
+            "This may be due to network issues or incorrect connection string."
+          );
+        }
+        console.error("Connection options:", JSON.stringify(opts, null, 2));
+        console.error("Stack trace:", error.stack);
         throw error;
       });
   }
 
-  console.log(999);
-
   try {
     cached.conn = await cached.promise;
   } catch (e) {
     cached.promise = null;
-    console.error("Failed to connect to MongoDB:", e);
+    console.error("Failed to establish database connection:");
+    console.error(e);
     throw e;
   }
 
   return cached.conn;
 }
 
-export default dbConnect;
+// Helper function to close the database connection
+async function closeDbConnection() {
+  if (cached.conn) {
+    await cached.conn.disconnect();
+    cached.conn = null;
+    cached.promise = null;
+    console.log("Database connection closed");
+  }
+}
+
+// Graceful shutdown
+process.on("SIGINT", async () => {
+  await closeDbConnection();
+  process.exit(0);
+});
+
+export { dbConnect, closeDbConnection };