dbConnect.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // dbConnect.js
  2. import mongoose from "mongoose";
  3. const MONGODB_URI = process.env.MONGODB_URI;
  4. const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase"; // 添加数据库名称
  5. if (!MONGODB_URI) {
  6. throw new Error(
  7. "Please define the MONGODB_URI environment variable inside .env.local"
  8. );
  9. }
  10. let cached = global.mongoose;
  11. if (!cached) {
  12. cached = global.mongoose = { conn: null, promise: null };
  13. }
  14. async function dbConnect() {
  15. if (cached.conn) {
  16. return cached.conn;
  17. }
  18. if (!cached.promise) {
  19. const opts = {
  20. bufferCommands: false,
  21. dbName: DB_NAME, // 明确指定数据库名称
  22. useNewUrlParser: true,
  23. useUnifiedTopology: true,
  24. };
  25. cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
  26. console.log(`Connected to MongoDB database: ${DB_NAME}`);
  27. return mongoose;
  28. });
  29. }
  30. try {
  31. cached.conn = await cached.promise;
  32. } catch (e) {
  33. cached.promise = null;
  34. console.error("Failed to connect to MongoDB:", e);
  35. throw e;
  36. }
  37. return cached.conn;
  38. }
  39. export default dbConnect;