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