alexcdev1 6 meses atrás
pai
commit
9967a5373f
1 arquivos alterados com 21 adições e 13 exclusões
  1. 21 13
      src/app/lib/dbConnect.js

+ 21 - 13
src/app/lib/dbConnect.js

@@ -2,7 +2,7 @@
 import mongoose from "mongoose";
 
 const MONGODB_URI = process.env.MONGODB_URI;
-const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase"; // 添加数据库名称
+const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase";
 
 console.log("DB_NAME", DB_NAME, MONGODB_URI);
 
@@ -12,37 +12,45 @@ if (!MONGODB_URI) {
   );
 }
 
-console.log("Database connected, starting query 111");
-
 let cached = global.mongoose;
 
 if (!cached) {
   cached = global.mongoose = { conn: null, promise: null };
 }
 
-console.log("Database connected, starting query 222");
-
 async function dbConnect() {
-  console.log("Database connected, starting query 333");
+  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,
+      dbName: DB_NAME,
     };
 
-    cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
-      console.log(`Connected to MongoDB database: ${DB_NAME}`);
-      return mongoose;
-    });
+    console.log("Attempting to connect to MongoDB...");
+    cached.promise = mongoose
+      .connect(MONGODB_URI, opts)
+      .then((mongoose) => {
+        console.log(`Connected to MongoDB database: ${DB_NAME}`);
+        return mongoose;
+      })
+      .catch((error) => {
+        console.error("Error connecting to MongoDB:", error);
+        throw error;
+      });
   }
 
+  console.log(999);
+
   try {
     cached.conn = await cached.promise;
   } catch (e) {