@@ -6,56 +6,20 @@ if (!MONGODB_URI) {
66 throw new Error ( 'Please define the MONGODB_URI environment variable' ) ;
77}
88
9- // Type the global object with our custom property
10- const globalWithMongoose = global as typeof globalThis & {
11- _mongooseCache ?: {
12- conn : typeof mongoose | null ;
13- promise : Promise < typeof mongoose > | null ;
14- } ;
15- } ;
16-
17- // Initialize the cache if it doesn't exist
18- if ( ! globalWithMongoose . _mongooseCache ) {
19- globalWithMongoose . _mongooseCache = { conn : null , promise : null } ;
20- }
21-
229export async function connectDB ( ) {
23- // At this point we know _mongooseCache exists because we initialized it above
24- const mongooseCache = globalWithMongoose . _mongooseCache ! ;
25-
26- if ( mongooseCache . conn ) {
27- return mongooseCache . conn ;
28- }
29-
30- if ( ! mongooseCache . promise ) {
31- const opts = {
32- bufferCommands : false ,
33- } ;
34-
35- mongooseCache . promise = mongoose . connect ( MONGODB_URI ! , opts ) . then ( ( mongoose ) => {
36- return mongoose ;
37- } ) ;
38- }
39-
4010 try {
41- const mongoose = await mongooseCache . promise ;
42- mongooseCache . conn = mongoose ;
11+ await mongoose . connect ( MONGODB_URI || '' ) ;
4312 console . log ( 'Connected to MongoDB' ) ;
4413 return mongoose ;
45- } catch ( e ) {
46- mongooseCache . promise = null ;
47- console . error ( 'MongoDB connection error:' , e ) ;
48- throw e ;
14+ } catch ( error ) {
15+ console . error ( 'MongoDB connection error:' , error ) ;
16+ throw error ;
4917 }
5018}
5119
5220export async function disconnectDB ( ) {
5321 try {
5422 await mongoose . disconnect ( ) ;
55- // At this point we know _mongooseCache exists because we initialized it above
56- const mongooseCache = globalWithMongoose . _mongooseCache ! ;
57- mongooseCache . conn = null ;
58- mongooseCache . promise = null ;
5923 console . log ( 'Disconnected from MongoDB' ) ;
6024 } catch ( error ) {
6125 console . error ( 'MongoDB disconnection error:' , error ) ;
0 commit comments