Task: "Create Mongoose databse function" Description: "Generate Mongoose databse…
- User
User: Task: "Create Mongoose databse function" Description: "Generate Mongoose databse setup on seprate file " Requirements: - Database: mongoose - Authentication: None specified - Output needed: Return only the function code as specified in dependencies - Dependencies: Import mongoose lirbary as DB, Create a global connection for DB, Handel all error that form from Database side. and connection errors also, DB should export from the file that can use all portion of the application - Previous Code // Import the mongoose library as DB const DB = mongoose;
// Create a function to set up the database connection function setupDatabaseConnection() { // Define the connection string const dbURI = 'mongodb://localhost:27017/yourDatabaseName';
code// Use the global mongoose Promise DB.Promise = global.Promise; // Connect to the MongoDB database using mongoose DB.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('Successfully connected to the database'); }) .catch((error) => { console.error('Error connecting to the database:', error); }); // Listen for DB connection success DB.connection.on('connected', () => { console.log('Mongoose connected to the database'); }); // Listen for DB connection error DB.connection.on('error', (err) => { console.error(`Mongoose connection error: ${err}`); }); // Listen for DB connection disconnection DB.connection.on('disconnected', () => { console.log('Mongoose disconnected from the database'); }); // Handle any uncaught errors in mongoose process.on('SIGINT', async () => { await DB.connection.close(); console.log('Mongoose disconnected due to application termination'); process.exit(0); });}
// Export the database connection for use throughout the application module.exports = { setupDatabaseConnection, DB: mongoose };
code - Assistantdependencies