From 41f7c978df5d8dcf1ace36db41f164e1c6bb9320 Mon Sep 17 00:00:00 2001 From: shweta10101 <141821678+shweta10101@users.noreply.github.com> Date: Fri, 11 Oct 2024 11:34:10 +0530 Subject: [PATCH 1/2] Update database.js Lack of Connection Pooling and Retry Mechanism Problem: In cloud environments, databases may experience temporary downtime. The current connection code does not handle retries or use connection pooling. Solution: Implement a retry mechanism and enable connection pooling by configuring the MongoClient in database.js. --- config/database.js | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/config/database.js b/config/database.js index 7553abb..abbe10e 100644 --- a/config/database.js +++ b/config/database.js @@ -1,3 +1,20 @@ -module.exports = { - mongoURI: 'mongodb://localhost/tododb-dev' -} +const mongoose = require('mongoose'); + +const options = { + useNewUrlParser: true, + useUnifiedTopology: true, + poolSize: 10, // Maintain up to 10 socket connections + serverSelectionTimeoutMS: 5000, // Retry for 5 seconds + socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity +}; + +// Enable detailed logging for MongoDB queries to track performance +mongoose.set('debug', true); + +mongoose.connect(process.env.MONGO_URI || 'mongodb://localhost/tododb-dev', options) + .then(() => console.log('Database connected successfully')) + .catch((err) => { + console.error('Initial connection error:', err); + process.exit(1); + }); + From 29bba11b36e7a9b9945d8f0f0a06ad623f8b16f4 Mon Sep 17 00:00:00 2001 From: shweta10101 <141821678+shweta10101@users.noreply.github.com> Date: Fri, 11 Oct 2024 11:36:25 +0530 Subject: [PATCH 2/2] Update Todo.js No Indexing on MongoDB Collections Problem: MongoDB collections might become slower as data grows. Indexing can greatly improve query performance, especially in cloud environments with larger datasets. Solution: Add indexing to the Todo and User models to ensure efficient querying. --- models/Todo.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/models/Todo.js b/models/Todo.js index acb767a..0748753 100644 --- a/models/Todo.js +++ b/models/Todo.js @@ -24,4 +24,7 @@ const TodoSchema = new Schema({ } }); -mongoose.model('todos', TodoSchema); \ No newline at end of file +// Add indexing for faster queries +TodoSchema.index({ title: 1, user: 1 }); + +mongoose.model('todos', TodoSchema);