Files
ksr/backend/scripts/migrate-json-to-mongo.js
2026-07-02 22:13:33 +02:00

73 lines
2.1 KiB
JavaScript

// Einmaliges Migrationsskript: liest eine alte data.json (aus der
// JSON-Datei-Version der App) und schreibt die Inhalte nach MongoDB.
//
// Nutzung:
// MONGODB_URI=mongodb://user:pass@host:27017 \
// node scripts/migrate-json-to-mongo.js /pfad/zu/data.json
//
// Das Skript ist idempotent-freundlich: bestehende Dokumente mit gleicher
// _id werden ueberschrieben (upsert), es entstehen keine Duplikate bei
// mehrfacher Ausfuehrung.
const fs = require("fs");
const { MongoClient } = require("mongodb");
async function main() {
const filePath = process.argv[2];
if (!filePath) {
console.error("Bitte Pfad zur data.json angeben.");
console.error("Beispiel: node scripts/migrate-json-to-mongo.js ./data.json");
process.exit(1);
}
if (!fs.existsSync(filePath)) {
console.error(`Datei nicht gefunden: ${filePath}`);
process.exit(1);
}
const raw = fs.readFileSync(filePath, "utf-8");
const data = JSON.parse(raw);
const uri = process.env.MONGODB_URI || "mongodb://localhost:27017";
const dbName = process.env.MONGODB_DB || "jahresplanung";
const client = new MongoClient(uri);
await client.connect();
const db = client.db(dbName);
const collections = {
people: data.people || [],
projects: data.projects || [],
tasks: data.tasks || [],
absences: data.absences || []
};
for (const [name, items] of Object.entries(collections)) {
if (items.length === 0) {
console.log(`- ${name}: keine Eintraege, uebersprungen`);
continue;
}
const ops = items.map((item) => {
const { id, ...rest } = item; // "id" -> "_id" umbenennen
return {
replaceOne: {
filter: { _id: id },
replacement: { _id: id, ...rest },
upsert: true
}
};
});
const result = await db.collection(name).bulkWrite(ops);
console.log(
`- ${name}: ${result.upsertedCount} neu, ${result.modifiedCount} aktualisiert`
);
}
await client.close();
console.log("Migration abgeschlossen.");
}
main().catch((err) => {
console.error("Migration fehlgeschlagen:", err);
process.exit(1);
});