#!/usr/bin/env node /** * Re-seed Photo documents from existing uploads when Mongo data is lost. * - One doc per webp file on disk. * - Captions default to filename without suffix. * - Tags default to ['uncategorized'] unless a prefix is present. * - Variants NOT linked; each file is its own doc. * * Usage: node scripts/reseed_uploads.js * Make sure MONGO_URI is set (or uses default). */ const fs = require('fs'); const path = require('path'); const mongoose = require('mongoose'); const Photo = require('../models/photo'); const MONGO_URI = process.env.MONGO_URI || 'mongodb://localhost:27017/photogallery'; const UPLOAD_DIR = path.join(__dirname, '..', 'uploads'); const VARIANT_SUFFIXES = { '': 'main', '-md': 'medium', '-sm': 'thumb' }; function parseFilename(file) { const ext = path.extname(file); const base = path.basename(file, ext); const matched = base.match(/(.+?)(-md|-sm)?$/); if (!matched) return { baseName: base, variant: 'main', ext }; const baseName = matched[1]; const variant = VARIANT_SUFFIXES[matched[2] || ''] || 'main'; return { baseName, variant, ext }; } async function main() { await mongoose.connect(MONGO_URI); console.log('Connected to Mongo:', MONGO_URI); const files = fs.readdirSync(UPLOAD_DIR).filter(f => f.toLowerCase().endsWith('.webp')); let created = 0; for (const file of files) { const existing = await Photo.findOne({ filename: file }); if (existing) continue; const baseName = path.basename(file, path.extname(file)); const caption = baseName.replace(/[-_]+/g, ' '); const tag = baseName.split('-')[1] || 'uncategorized'; const doc = new Photo({ filename: file, path: path.join('uploads', file), caption, tags: [tag], }); await doc.save(); created++; } console.log(`Seed complete. Created ${created} photo documents.`); await mongoose.disconnect(); } main().catch(err => { console.error(err); process.exit(1); });