diff --git a/server/routers/procurement/config/db.js b/server/routers/procurement/config/db.js index 31e7ae4..0e3adf3 100644 --- a/server/routers/procurement/config/db.js +++ b/server/routers/procurement/config/db.js @@ -2,10 +2,10 @@ const mongoose = require('mongoose'); const connectDB = async () => { try { - const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/procurement_db'; + const mongoUri = process.env.MONGODB_URI || 'mongodb://admin:password@localhost:27017/procurement_db?authSource=admin'; console.log('\n📡 Попытка подключения к MongoDB...'); - console.log(` URI: ${mongoUri}`); + console.log(` URI: ${mongoUri.replace(/\/\/:.*@/, '//***:***@')}`); const connection = await mongoose.connect(mongoUri, { useNewUrlParser: true, diff --git a/server/routers/procurement/index.js b/server/routers/procurement/index.js index 1f29b3d..fdbc8fd 100644 --- a/server/routers/procurement/index.js +++ b/server/routers/procurement/index.js @@ -43,7 +43,7 @@ const initializeApp = async () => { // Запустить миграции после успешного подключения if (dbConnected) { try { - await runMigrations(); + await runMigrations(false); migrationsCompleted = true; } catch (migrationError) { console.error('⚠️ Migrations failed but app will continue:', migrationError.message); diff --git a/server/routers/procurement/scripts/init-database.js b/server/routers/procurement/scripts/init-database.js index 819bbff..afae63b 100644 --- a/server/routers/procurement/scripts/init-database.js +++ b/server/routers/procurement/scripts/init-database.js @@ -2,7 +2,7 @@ const mongoose = require('mongoose'); const { migrateCompanies } = require('./migrate-companies'); require('dotenv').config({ path: '../../.env' }); -const mongoUrl = process.env.MONGODB_URI || 'mongodb://localhost:27017/procurement_db'; +const mongoUrl = process.env.MONGODB_URI || 'mongodb://admin:password@localhost:27017/procurement_db?authSource=admin'; // Migration history model const migrationSchema = new mongoose.Schema({ diff --git a/server/routers/procurement/scripts/migrate-messages.js b/server/routers/procurement/scripts/migrate-messages.js index 56a877e..dba2b66 100644 --- a/server/routers/procurement/scripts/migrate-messages.js +++ b/server/routers/procurement/scripts/migrate-messages.js @@ -6,14 +6,17 @@ const mongoUrl = process.env.MONGODB_URI || 'mongodb://localhost:27017/procureme async function migrateMessages() { try { - console.log('[Migration] Connecting to MongoDB...'); - await mongoose.connect(mongoUrl, { - useNewUrlParser: true, - useUnifiedTopology: true, - serverSelectionTimeoutMS: 5000, - connectTimeoutMS: 5000, - }); - console.log('[Migration] Connected to MongoDB'); + // Check if connection exists, if not connect + if (mongoose.connection.readyState === 0) { + console.log('[Migration] Connecting to MongoDB...'); + await mongoose.connect(mongoUrl, { + useNewUrlParser: true, + useUnifiedTopology: true, + serverSelectionTimeoutMS: 5000, + connectTimeoutMS: 5000, + }); + console.log('[Migration] Connected to MongoDB'); + } // Найти все сообщения const allMessages = await Message.find().exec(); @@ -81,9 +84,6 @@ async function migrateMessages() { console.log('[Migration] ✅ Migration completed!'); console.log('[Migration] Fixed:', fixedCount, 'messages'); console.log('[Migration] Errors:', errorCount); - - await mongoose.connection.close(); - console.log('[Migration] Disconnected from MongoDB'); } catch (err) { console.error('[Migration] ❌ Error:', err.message); throw err; diff --git a/server/routers/procurement/scripts/run-migrations.js b/server/routers/procurement/scripts/run-migrations.js index d2dde49..1c59fbc 100644 --- a/server/routers/procurement/scripts/run-migrations.js +++ b/server/routers/procurement/scripts/run-migrations.js @@ -4,7 +4,7 @@ const { migrateMessages } = require('./migrate-messages'); const { recreateTestUser } = require('./recreate-test-user'); require('dotenv').config(); -const mongoUrl = process.env.MONGODB_URI || 'mongodb://localhost:27017/procurement_db'; +const mongoUrl = process.env.MONGODB_URI || 'mongodb://admin:password@localhost:27017/procurement_db?authSource=admin'; // Migration history model const migrationSchema = new mongoose.Schema({ @@ -22,7 +22,7 @@ const migrations = [ { name: 'recreate-test-user', fn: recreateTestUser } ]; -async function runMigrations() { +async function runMigrations(shouldCloseConnection = false) { let mongooseConnected = false; try { @@ -30,15 +30,20 @@ async function runMigrations() { console.log('🚀 Starting Database Migrations'); console.log('='.repeat(60) + '\n'); - console.log('[Migrations] Connecting to MongoDB...'); - await mongoose.connect(mongoUrl, { - useNewUrlParser: true, - useUnifiedTopology: true, - serverSelectionTimeoutMS: 5000, - connectTimeoutMS: 5000, - }); - mongooseConnected = true; - console.log('[Migrations] ✅ Connected to MongoDB\n'); + // Only connect if not already connected + if (mongoose.connection.readyState === 0) { + console.log('[Migrations] Connecting to MongoDB...'); + await mongoose.connect(mongoUrl, { + useNewUrlParser: true, + useUnifiedTopology: true, + serverSelectionTimeoutMS: 5000, + connectTimeoutMS: 5000, + }); + mongooseConnected = true; + console.log('[Migrations] ✅ Connected to MongoDB\n'); + } else { + console.log('[Migrations] ✅ Using existing MongoDB connection\n'); + } for (const migration of migrations) { console.log(`[${migration.name}] Starting...`); @@ -67,22 +72,17 @@ async function runMigrations() { console.log(`[${migration.name}] ✅ Completed and recorded\n`); } catch (error) { - // Обработка ошибок аутентификации и других ошибок - if (error.message && error.message.includes('authentication')) { - console.warn(`[${migration.name}] ⚠️ Skipped (authentication required): ${error.message}\n`); - } else { - console.error(`[${migration.name}] ❌ Error: ${error.message}\n`); + console.error(`[${migration.name}] ❌ Error: ${error.message}\n`); - // Record failed migration - try { - await Migration.create({ - name: migration.name, - status: 'failed', - message: error.message - }); - } catch (recordErr) { - // Ignore if we can't record the failure - } + // Record failed migration + try { + await Migration.create({ + name: migration.name, + status: 'failed', + message: error.message + }); + } catch (recordErr) { + // Ignore if we can't record the failure } } } @@ -92,17 +92,14 @@ async function runMigrations() { console.log('='.repeat(60) + '\n'); } catch (error) { - // Обработка ошибок подключения - if (error.message && error.message.includes('authentication')) { - console.warn('\n⚠️ Database authentication required - migrations skipped'); - console.warn('This is normal if the database is shared with other projects.\n'); - } else { - console.error('\n❌ Fatal migration error:', error.message); - console.error(error); + console.error('\n❌ Fatal migration error:', error.message); + console.error(error); + if (shouldCloseConnection) { process.exit(1); } } finally { - if (mongooseConnected) { + // Only close connection if we created it and requested to close + if (mongooseConnected && shouldCloseConnection) { await mongoose.connection.close(); console.log('[Migrations] Disconnected from MongoDB\n'); } @@ -113,7 +110,7 @@ module.exports = { runMigrations, Migration }; // Run directly if called as script if (require.main === module) { - runMigrations().catch(err => { + runMigrations(true).catch(err => { console.error('Migration failed:', err); process.exit(1); }); diff --git a/server/utils/const.ts b/server/utils/const.ts index 3ab73e4..70afa42 100644 --- a/server/utils/const.ts +++ b/server/utils/const.ts @@ -1,4 +1,4 @@ import 'dotenv/config'; // Connection URL -export const mongoUrl = process.env.MONGO_ADDR || 'mongodb://localhost:27017' +export const mongoUrl = process.env.MONGO_ADDR || 'mongodb://admin:password@localhost:27017/procurement_db?authSource=admin';