From e9e5eb32addde834c88c716c5db034ceb0d98942 Mon Sep 17 00:00:00 2001 From: Bangara Raju Kottedi Date: Wed, 28 Jan 2026 15:54:33 +0530 Subject: [PATCH] Update MongoDB connection settings and enhance debugging capabilities --- .env | 2 +- Dockerfile | 2 +- backend/.env | 5 ++++ backend/.env.example | 3 --- backend/config/database.js | 7 ++++- backend/config/session.js | 37 ++++++++++++++++++++++++--- backend/server.js | 5 +++- backend/test-connection-no-replica.js | 22 ++++++++++++++++ backend/test-connection.js | 27 +++++++++++++++++++ backend/test-mongo-debug.js | 23 +++++++++++++++++ backend/test-network.js | 34 ++++++++++++++++++++++++ package-lock.json | 1 + src/App.js | 4 ++- src/index.js | 2 +- 14 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 backend/.env delete mode 100644 backend/.env.example create mode 100644 backend/test-connection-no-replica.js create mode 100644 backend/test-connection.js create mode 100644 backend/test-mongo-debug.js create mode 100644 backend/test-network.js diff --git a/.env b/.env index 6395606..cfc913c 100644 --- a/.env +++ b/.env @@ -1,5 +1,5 @@ # MongoDB connection for backend -CONNECTION_URI=mongodb://admin:adminpassword@mongo:27017/ludo?authSource=admin&replicaSet=rs0 +CONNECTION_URI=mongodb://admin:adminpassword@192.168.0.197:27017/ludo?authSource=admin&replicaSet=rs0 # Backend port PORT=18081 diff --git a/Dockerfile b/Dockerfile index cb1ab41..70bb90f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -103,7 +103,7 @@ RUN chmod +x wait-for-mongo.sh # Default fallback values (can be overridden by Compose) ENV NODE_ENV=production ENV PORT=8080 -ENV CONNECTION_URI=mongodb://mongo:27017/ludo?replicaSet=rs0 +ENV CONNECTION_URI=mongodb://192.168.0.197:27017/ludo?replicaSet=rs0 EXPOSE 18081 diff --git a/backend/.env b/backend/.env new file mode 100644 index 0000000..5ea659f --- /dev/null +++ b/backend/.env @@ -0,0 +1,5 @@ +PORT=8080 +# MongoDB connection for backend +CONNECTION_URI=mongodb://admin:adminpassword@192.168.0.197:27017/ludo?authSource=admin&replicaSet=rs0 + +NODE_ENV="development" \ No newline at end of file diff --git a/backend/.env.example b/backend/.env.example deleted file mode 100644 index 52a81f1..0000000 --- a/backend/.env.example +++ /dev/null @@ -1,3 +0,0 @@ -PORT=8080 -CONNECTION_URI=your_mongodb_connection_uri -NODE_ENV="development" \ No newline at end of file diff --git a/backend/config/database.js b/backend/config/database.js index 4d5542f..793a085 100644 --- a/backend/config/database.js +++ b/backend/config/database.js @@ -1,6 +1,11 @@ module.exports = async function (mongoose) { try { - await mongoose.connect(process.env.CONNECTION_URI); + console.log('🔌 Attempting to connect with URI:', process.env.CONNECTION_URI); + await mongoose.connect(process.env.CONNECTION_URI, { + useNewUrlParser: true, + useUnifiedTopology: true, + directConnection: true, + }); console.log('✅ MongoDB connected'); } catch (err) { console.error('❌ MongoDB connection error:', err); diff --git a/backend/config/session.js b/backend/config/session.js index c66fb40..c2f2a74 100644 --- a/backend/config/session.js +++ b/backend/config/session.js @@ -1,10 +1,41 @@ const session = require('express-session'); const MongoDBStore = require('connect-mongodb-session')(session); -const store = new MongoDBStore({ - uri: process.env.CONNECTION_URI, +console.log('📋 Session.js - CONNECTION_URI:', process.env.CONNECTION_URI); + +// Parse the connection URI to extract connection options +const uriString = process.env.CONNECTION_URI; +const uriUrl = new URL(uriString); + +// Extract individual components +const baseUri = `${uriUrl.protocol}//${uriUrl.username}:${uriUrl.password}@${uriUrl.hostname}:${uriUrl.port}${uriUrl.pathname}`; +const replicaSet = uriUrl.searchParams.get('replicaSet'); +const authSource = uriUrl.searchParams.get('authSource'); + +console.log('📋 Base URI:', baseUri); +console.log('📋 ReplicaSet:', replicaSet); +console.log('📋 AuthSource:', authSource); + +// Build connection options with directConnection to bypass replica set discovery +const connectionOptions = { + useNewUrlParser: true, + useUnifiedTopology: true, + directConnection: true, // Force direct connection to specified server +}; + +if (authSource) { + connectionOptions.authSource = authSource; +} + +const storeOptions = { + uri: baseUri, collection: 'sessions', -}); + connectionOptions: connectionOptions, +}; + +console.log('📋 Store options:', JSON.stringify(storeOptions, null, 2)); + +const store = new MongoDBStore(storeOptions); const sessionMiddleware = session({ store: store, credentials: true, diff --git a/backend/server.js b/backend/server.js index 5e2e212..5aea1ba 100644 --- a/backend/server.js +++ b/backend/server.js @@ -3,11 +3,14 @@ const cors = require('cors'); const path = require('path'); const cookieParser = require('cookie-parser'); const mongoose = require('mongoose'); -require('dotenv').config(); +require('dotenv').config({ path: path.join(__dirname, '.env') }); const { sessionMiddleware } = require('./config/session'); const PORT = process.env.PORT || 5000; +console.log('🔍 Environment loaded from:', path.join(__dirname, '.env')); +console.log('📍 Connection URI:', process.env.CONNECTION_URI); + const app = express(); app.use(cookieParser()); diff --git a/backend/test-connection-no-replica.js b/backend/test-connection-no-replica.js new file mode 100644 index 0000000..a8433b6 --- /dev/null +++ b/backend/test-connection-no-replica.js @@ -0,0 +1,22 @@ +const mongodb = require('mongodb'); +require('dotenv').config({ path: require('path').join(__dirname, '.env') }); + +// Try without replicaSet +const uri = 'mongodb://admin:adminpassword@192.168.0.197:27017/ludo?authSource=admin'; +console.log('Testing without replicaSet:', uri); + +mongodb.MongoClient.connect(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + authSource: 'admin', + serverSelectionTimeoutMS: 5000, +}, (err, client) => { + if (err) { + console.error('❌ Connection error:', err.message); + process.exit(1); + } else { + console.log('✅ Connected successfully!'); + client.close(); + process.exit(0); + } +}); diff --git a/backend/test-connection.js b/backend/test-connection.js new file mode 100644 index 0000000..9d48890 --- /dev/null +++ b/backend/test-connection.js @@ -0,0 +1,27 @@ +const mongodb = require('mongodb'); +require('dotenv').config({ path: require('path').join(__dirname, '.env') }); + +const uri = process.env.CONNECTION_URI; +console.log('Testing with URI:', uri); + +const uriUrl = new URL(uri); +console.log('URL components:'); +console.log(' hostname:', uriUrl.hostname); +console.log(' port:', uriUrl.port); +console.log(' pathname:', uriUrl.pathname); +console.log(' searchParams:', Object.fromEntries(uriUrl.searchParams)); + +// Try to connect directly +mongodb.MongoClient.connect(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + replicaSet: 'rs0', + authSource: 'admin' +}, (err, client) => { + if (err) { + console.error('Connection error:', err.message); + } else { + console.log('✅ Connected successfully!'); + client.close(); + } +}); diff --git a/backend/test-mongo-debug.js b/backend/test-mongo-debug.js new file mode 100644 index 0000000..bc5a734 --- /dev/null +++ b/backend/test-mongo-debug.js @@ -0,0 +1,23 @@ +process.env.DEBUG = 'mongodb:*'; + +const mongodb = require('mongodb'); + +const uri = 'mongodb://admin:adminpassword@192.168.0.197:27017/ludo?authSource=admin'; +console.log('Connecting to:', uri); + +const client = new mongodb.MongoClient(uri, { + useNewUrlParser: true, + useUnifiedTopology: true, + authSource: 'admin', + serverSelectionTimeoutMS: 3000, + loggerLevel: 'debug', +}); + +client.connect((err) => { + if (err) { + console.error('❌ Connection error:', err); + } else { + console.log('✅ Connected!'); + client.close(); + } +}); diff --git a/backend/test-network.js b/backend/test-network.js new file mode 100644 index 0000000..9d95cd0 --- /dev/null +++ b/backend/test-network.js @@ -0,0 +1,34 @@ +const mongodb = require('mongodb'); +const net = require('net'); +const dns = require('dns').promises; + +async function test() { + // Test DNS resolution + console.log('Testing DNS resolution...'); + try { + const res = await dns.resolve4('192.168.0.197'); + console.log('DNS resolve4(192.168.0.197):', res); + } catch (e) { + console.log('DNS error:', e.message); + } + + try { + const res = await dns.resolve4('mongo'); + console.log('DNS resolve4(mongo):', res); + } catch (e) { + console.log('DNS mongo error:', e.message); + } + + // Test direct socket connection + console.log('\nTesting direct TCP connection...'); + const socket = net.createConnection(27017, '192.168.0.197'); + socket.on('connect', () => { + console.log('✅ TCP connection successful to 192.168.0.197:27017'); + socket.destroy(); + }); + socket.on('error', (err) => { + console.log('❌ TCP connection error:', err.message); + }); +} + +test(); diff --git a/package-lock.json b/package-lock.json index b6d4725..c2027ab 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,6 +26,7 @@ "web-vitals": "^3.5.0" }, "devDependencies": { + "@babel/plugin-transform-private-property-in-object": "^7.16.7", "@testing-library/jest-dom": "^6.1.5", "@testing-library/react": "^14.1.2", "cypress": "^13.6.1" diff --git a/src/App.js b/src/App.js index 24fa56a..61034eb 100644 --- a/src/App.js +++ b/src/App.js @@ -13,7 +13,7 @@ function App() { const [playerSocket, setPlayerSocket] = useState(); const [redirect, setRedirect] = useState(); useEffect(() => { - const socket = io(`${window.location.protocol}//${window.location.host}`, { withCredentials: true }); + const socket = io(`http://${window.location.hostname}:8080`, { withCredentials: true }); socket.on('player:data', data => { data = JSON.parse(data); setPlayerData(data); @@ -72,3 +72,5 @@ function App() { ); } + +export default App; diff --git a/src/index.js b/src/index.js index 8e269be..627d623 100644 --- a/src/index.js +++ b/src/index.js @@ -1,7 +1,7 @@ import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; -import App from './App'; +import App from './App.js'; const container = document.getElementById('root'); const root = ReactDOM.createRoot(container);