Initial
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
async function connectDB() {
|
||||
const uri = process.env.MONGODB_URI;
|
||||
if (!uri) {
|
||||
throw new Error('MONGODB_URI ist nicht gesetzt.');
|
||||
}
|
||||
|
||||
const maxRetries = 10;
|
||||
let attempt = 0;
|
||||
|
||||
// Beim Start mit docker-compose ist die MongoDB manchmal noch nicht
|
||||
// bereit, deshalb versuchen wir es mit kurzer Pause mehrmals.
|
||||
while (attempt < maxRetries) {
|
||||
try {
|
||||
await mongoose.connect(uri);
|
||||
console.log('MongoDB verbunden.');
|
||||
return;
|
||||
} catch (err) {
|
||||
attempt += 1;
|
||||
console.error(
|
||||
`MongoDB-Verbindung fehlgeschlagen (Versuch ${attempt}/${maxRetries}): ${err.message}`
|
||||
);
|
||||
if (attempt >= maxRetries) throw err;
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { connectDB };
|
||||
Reference in New Issue
Block a user