This commit is contained in:
2025-10-27 20:04:02 +03:00
parent 390d97e6d5
commit 35493a09b5
6 changed files with 48 additions and 51 deletions

View File

@@ -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,

View File

@@ -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);

View File

@@ -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({

View File

@@ -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;

View File

@@ -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);
});

View File

@@ -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';