dbConnect.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. console.log("DB_NAME", DB_NAME, MONGODB_URI);
  6. if (!MONGODB_URI) {
  7. throw new Error(
  8. "Please define the MONGODB_URI environment variable inside .env.local"
  9. );
  10. }
  11. let cached = global.mongoose;
  12. if (!cached) {
  13. cached = global.mongoose = { conn: null, promise: null };
  14. }
  15. async function dbConnect() {
  16. console.log(666);
  17. if (cached.conn) {
  18. console.log("Using cached database connection");
  19. return cached.conn;
  20. }
  21. console.log(777);
  22. if (!cached.promise) {
  23. console.log(888);
  24. const opts = {
  25. bufferCommands: false,
  26. dbName: DB_NAME,
  27. };
  28. console.log("Attempting to connect to MongoDB...");
  29. cached.promise = mongoose
  30. .connect(MONGODB_URI, opts)
  31. .then((mongoose) => {
  32. console.log(`Connected to MongoDB database: ${DB_NAME}`);
  33. return mongoose;
  34. })
  35. .catch((error) => {
  36. console.error("Error connecting to MongoDB:", error);
  37. throw error;
  38. });
  39. }
  40. console.log(999);
  41. try {
  42. cached.conn = await cached.promise;
  43. } catch (e) {
  44. cached.promise = null;
  45. console.error("Failed to connect to MongoDB:", e);
  46. throw e;
  47. }
  48. return cached.conn;
  49. }
  50. export default dbConnect;