File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- const mongoose = require ( 'mongoose' ) ;
1+ const mongoose = require ( "mongoose" ) ;
2+
3+ let isConnected = false ;
24
35const connectDB = async ( ) => {
4- try {
5- await mongoose . connect ( process . env . DATABASE_URI , {
6- useUnifiedTopology : true ,
7- useNewUrlParser : true
8- } ) ;
9- } catch ( err ) {
10- console . error ( err ) ;
11- }
12- }
13-
14- module . exports = connectDB
6+ if ( isConnected ) {
7+ console . log ( "Using existing MongoDB connection" ) ;
8+ return ;
9+ }
10+
11+ try {
12+ console . log ( "Connecting to MongoDB..." ) ;
13+ console . log ( process . env . DATABASE_URI )
14+ const db = await mongoose . connect ( process . env . DATABASE_URI , {
15+ serverSelectionTimeoutMS : 5000 ,
16+ socketTimeoutMS : 45000 ,
17+ tls : true ,
18+ } ) ;
19+
20+ isConnected = db . connections [ 0 ] . readyState ;
21+
22+ console . log ( "MongoDB connected successfully" ) ;
23+ } catch ( error ) {
24+ console . error ( "MongoDB connection error:" , error ) ;
25+ throw error ;
26+ }
27+ } ;
28+
29+ module . exports = connectDB ;
You can’t perform that action at this time.
0 commit comments