Files
cms.uldp.edu.vn/scripts/seedAbout.js

53 lines
1.7 KiB
JavaScript

const mongoose = require("mongoose");
const dotenv = require("dotenv");
const fs = require("fs");
const path = require("path");
// Load environment variables
dotenv.config();
const AboutUs = require("../models/aboutUs");
const seedAbout = async () => {
try {
console.log("🚀 Starting About section seeding...");
// 1. Connect to MongoDB
if (!process.env.MONGODB_URI) {
throw new Error("MONGODB_URI is not defined in environment variables");
}
await mongoose.connect(process.env.MONGODB_URI);
console.log("✅ MongoDB Connected");
// 2. Read about.json (Single Source of Truth)
const jsonPath = path.join(__dirname, "../data/about.json");
if (!fs.existsSync(jsonPath)) {
throw new Error(`Source about.json not found at: ${jsonPath}`);
}
const rawData = fs.readFileSync(jsonPath, "utf8");
const jsonData = JSON.parse(rawData);
console.log("✅ Read data/about.json successfully");
// 3. Upsert logic (Singleton pattern)
// We look for any existing document and update it, or create a new one if none exists.
await AboutUs.findOneAndUpdate(
{},
jsonData,
{ upsert: true, new: true, setDefaultsOnInsert: true }
);
console.log("✅ Successfully seeded about.json data to MongoDB (Upserted)");
} catch (error) {
console.error("❌ Seeding failed:", error.message);
} finally {
// 4. Close connection
await mongoose.connection.close();
console.log("👋 Database connection closed");
process.exit(0);
}
};
seedAbout();