alexcdev1 il y a 6 mois
Parent
commit
63971f7038
1 fichiers modifiés avec 18 ajouts et 68 suppressions
  1. 18 68
      src/app/lib/dbConnect.js

+ 18 - 68
src/app/lib/dbConnect.js

@@ -1,9 +1,10 @@
+// dbConnect.js
 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);
+console.log("DB_NAME", DB_NAME, MONGODB_URI);
 
 if (!MONGODB_URI) {
   throw new Error(
@@ -11,97 +12,46 @@ 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");
+
   if (cached.conn) {
-    console.log("Using existing database connection");
     return cached.conn;
   }
 
   if (!cached.promise) {
     const opts = {
       bufferCommands: false,
-      dbName: DB_NAME,
-      // 移除了废弃的选项
+      dbName: DB_NAME, // 明确指定数据库名称
+      useNewUrlParser: true,
+      useUnifiedTopology: true,
     };
 
-    console.log("Creating new database connection");
-    console.log(`Connecting to database: ${DB_NAME}`);
-    console.log(`MongoDB URI: ${MONGODB_URI.replace(/:[^:]*@/, ":****@")}`);
-
-    cached.promise = mongoose
-      .connect(MONGODB_URI, opts)
-      .then((mongoose) => {
-        console.log(`Successfully connected to MongoDB: ${DB_NAME}`);
-        return mongoose;
-      })
-      .catch((error) => {
-        console.error("Error connecting to MongoDB:", error);
-        cached.promise = null;
-        throw error;
-      });
-  } else {
-    console.log("Using existing connection promise");
+    cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
+      console.log(`Connected to MongoDB database: ${DB_NAME}`);
+      return mongoose;
+    });
   }
 
   try {
     cached.conn = await cached.promise;
   } catch (e) {
     cached.promise = null;
-    console.error("Error while awaiting connection:", e);
+    console.error("Failed to connect to MongoDB:", e);
     throw e;
   }
 
   return cached.conn;
 }
 
-// 添加一个关闭连接的函数,用于测试或需要手动关闭连接的场景
-async function dbDisconnect() {
-  if (cached.conn) {
-    await mongoose.disconnect();
-    cached.conn = null;
-    cached.promise = null;
-    console.log("Disconnected from MongoDB");
-  }
-}
-
-// 添加一个用于调试的函数
-function getConnectionStatus() {
-  return {
-    readyState: mongoose.connection.readyState,
-    dbName: mongoose.connection.name,
-    host: mongoose.connection.host,
-    port: mongoose.connection.port,
-  };
-}
-
-// 设置 Mongoose 调试模式(在生产环境中应该禁用)
-if (process.env.NODE_ENV !== "production") {
-  mongoose.set("debug", true);
-}
-
-// 监听连接事件
-mongoose.connection.on("connected", () => {
-  console.log("Mongoose connected to db");
-});
-
-mongoose.connection.on("error", (err) => {
-  console.error("Mongoose connection error:", err);
-});
-
-mongoose.connection.on("disconnected", () => {
-  console.log("Mongoose disconnected");
-});
-
-// 处理应用程序终止,关闭数据库连接
-process.on("SIGINT", async () => {
-  await dbDisconnect();
-  process.exit(0);
-});
-
-export { dbConnect, dbDisconnect, getConnectionStatus };
+export default dbConnect;