-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathserver.js
More file actions
53 lines (44 loc) · 1.38 KB
/
server.js
File metadata and controls
53 lines (44 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import 'dotenv/config';
import mongoose from 'mongoose';
import app from './src/app.js';
const PORT = process.env.PORT || 5000;
/**
* Connect to MongoDB and start the Express server
*/
const startServer = async () => {
try {
// Check if MONGODB_URI is provided
if (!process.env.MONGODB_URI) {
console.error('❌ MONGODB_URI is not defined in environment variables');
process.exit(1);
}
// Connect to MongoDB
console.log('🔄 Connecting to MongoDB...');
await mongoose.connect(process.env.MONGODB_URI);
console.log(`✅ Connected to MongoDB: ${mongoose.connection.name}`);
// Start Express server
app.listen(PORT, () => {
console.log(`🚀 Server is running on port ${PORT}`);
console.log(`📊 Database: ${mongoose.connection.name}`);
});
} catch (error) {
console.error('❌ Failed to start server:', error.message);
process.exit(1);
}
};
// Handle MongoDB connection events
mongoose.connection.on('error', (err) => {
console.error('❌ MongoDB connection error:', err);
});
mongoose.connection.on('disconnected', () => {
console.warn('⚠️ MongoDB disconnected');
});
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\n🛑 Shutting down server...');
await mongoose.connection.close();
console.log('✅ MongoDB connection closed');
process.exit(0);
});
// Start the server
startServer();