63 lines
1.6 KiB
JavaScript
63 lines
1.6 KiB
JavaScript
const mongoose = require('mongoose');
|
|
require('./models'); // Load all schemas
|
|
|
|
/**
|
|
* Connect to MongoDB with reconnection logic
|
|
* @param {string} uri - MongoDB connection URI (from process.env.MONGODB_URI)
|
|
* @param {object} options - Optional Mongoose connection options
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function connectMongoDB(uri, options = {}) {
|
|
if (!uri) {
|
|
throw new Error('MONGODB_URI is required. Add it to your .env file.');
|
|
}
|
|
|
|
const defaultOptions = {
|
|
serverSelectionTimeoutMS: 5000,
|
|
socketTimeoutMS: 45000,
|
|
...options
|
|
};
|
|
|
|
try {
|
|
await mongoose.connect(uri, defaultOptions);
|
|
console.log('✓ Connected to MongoDB');
|
|
|
|
// Handle connection events
|
|
mongoose.connection.on('error', (err) => {
|
|
console.error('MongoDB connection error:', err);
|
|
});
|
|
|
|
mongoose.connection.on('disconnected', () => {
|
|
console.warn('MongoDB disconnected. Attempting to reconnect...');
|
|
});
|
|
|
|
mongoose.connection.on('reconnected', () => {
|
|
console.log('✓ MongoDB reconnected');
|
|
});
|
|
|
|
} catch (err) {
|
|
console.error('Failed to connect to MongoDB:', err.message);
|
|
console.error('Stack:', err.stack);
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Gracefully close MongoDB connection
|
|
* @returns {Promise<void>}
|
|
*/
|
|
async function closeMongoDB() {
|
|
try {
|
|
await mongoose.connection.close();
|
|
console.log('MongoDB connection closed');
|
|
} catch (err) {
|
|
console.error('Error closing MongoDB:', err);
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
connectMongoDB,
|
|
closeMongoDB,
|
|
mongoose
|
|
};
|