// dbConnect.js import mongoose from "mongoose"; const MONGODB_URI = process.env.MONGODB_URI; const DB_NAME = process.env.MONGODB_DB_NAME || "mydatabase"; console.log("DB_NAME", DB_NAME, MONGODB_URI); if (!MONGODB_URI) { throw new Error( "Please define the MONGODB_URI environment variable inside .env.local" ); } let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } async function dbConnect() { 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, }; 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) { cached.promise = null; console.error("Failed to connect to MongoDB:", e); throw e; } return cached.conn; } export default dbConnect;