myex-cli
Version:
Opinionated Express.js framework with CLI tools
40 lines (32 loc) • 1.06 kB
JavaScript
import mongoose from 'mongoose';
import { logger } from '../utils/logger.js';
/**
* Connect to MongoDB database
*/
export const connectToDatabase = async () => {
try {
const connectionString = process.env.MONGODB_URI;
// Set mongoose options
const options = {
serverSelectionTimeoutMS: 5000, // Timeout after 5s
};
await mongoose.connect(connectionString, options);
logger.info('Connected to MongoDB');
// Handle MongoDB connection events
mongoose.connection.on('error', (err) => {
logger.error(`MongoDB connection error: ${err}`);
});
mongoose.connection.on('disconnected', () => {
logger.warn('MongoDB disconnected');
});
// Handle application termination
process.on('SIGINT', async () => {
await mongoose.connection.close();
logger.info('MongoDB connection closed due to app termination');
process.exit(0);
});
} catch (error) {
logger.error(`Error connecting to MongoDB: ${error.message}`);
process.exit(1);
}
};