alexcdev1 il y a 6 mois
Parent
commit
066d5a841c
2 fichiers modifiés avec 8 ajouts et 28 suppressions
  1. 1 0
      .env.local
  2. 7 28
      src/app/lib/dbConnect.js

+ 1 - 0
.env.local

@@ -1,3 +1,4 @@
 # MONGODB_URI=mongodb+srv://admin:password123@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority
 # MONGODB_URI=mongodb://localhost:27017/mydatabase
 MONGODB_URI=mongodb+srv://alexcdev:MM2wUnaykoiK904j@cluster0.snuq8.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
+MONGODB_DB_NAME=mydatabase

+ 7 - 28
src/app/lib/dbConnect.js

@@ -2,6 +2,7 @@
 import mongoose from "mongoose";
 
 const MONGODB_URI = process.env.MONGODB_URI;
+const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase"; // 添加数据库名称
 
 if (!MONGODB_URI) {
   throw new Error(
@@ -23,17 +24,22 @@ async function dbConnect() {
   if (!cached.promise) {
     const opts = {
       bufferCommands: false,
+      dbName: DB_NAME, // 明确指定数据库名称
+      useNewUrlParser: true,
+      useUnifiedTopology: true,
     };
 
     cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
-      console.log("Connected to MongoDB");
+      console.log(`Connected to MongoDB database: ${DB_NAME}`);
       return mongoose;
     });
   }
+
   try {
     cached.conn = await cached.promise;
   } catch (e) {
     cached.promise = null;
+    console.error("Failed to connect to MongoDB:", e);
     throw e;
   }
 
@@ -41,30 +47,3 @@ async function dbConnect() {
 }
 
 export default dbConnect;
-
-// import { MongoClient } from "mongodb";
-
-// const MONGODB_URI = process.env.MONGODB_URI;
-// let cachedClient = null;
-
-// export default async function dbConnect() {
-//   if (cachedClient) {
-//     return cachedClient;
-//   }
-
-//   if (!MONGODB_URI) {
-//     throw new Error(
-//       "Please define the MONGODB_URI environment variable inside .env.local"
-//     );
-//   }
-
-//   const client = new MongoClient(MONGODB_URI, {
-//     useNewUrlParser: true,
-//     useUnifiedTopology: true,
-//   });
-
-//   await client.connect();
-//   cachedClient = client;
-
-//   return client;
-// }