forked from UKSOURCE/cms.hailearning.edu.vn
70 lines
2.0 KiB
JavaScript
70 lines
2.0 KiB
JavaScript
const mongoose = require('mongoose');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const dotenv = require('dotenv');
|
|
const HeaderMenu = require('../models/headerMenu');
|
|
|
|
dotenv.config();
|
|
|
|
const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost:27017/SIMS';
|
|
|
|
async function connectDB() {
|
|
try {
|
|
await mongoose.connect(MONGODB_URI);
|
|
console.log('✅ MongoDB Connected for Migration');
|
|
} catch (err) {
|
|
console.error('❌ MongoDB Connection Error:', err);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
const processMenuItems = async (items, parentId = null) => {
|
|
for (const item of items) {
|
|
console.log(` > Importing: ${item.label}`);
|
|
|
|
const menuDoc = {
|
|
title: item.label,
|
|
slug: item.slug,
|
|
url: item.href,
|
|
parentId: parentId,
|
|
order: item.order || 0,
|
|
status: item.isActive === false ? "inactive" : "active",
|
|
type: item.type === "external" ? "external" : "internal"
|
|
};
|
|
|
|
const createdItem = await HeaderMenu.create(menuDoc);
|
|
|
|
if (item.children && item.children.length > 0) {
|
|
await processMenuItems(item.children, createdItem._id);
|
|
}
|
|
}
|
|
};
|
|
|
|
async function migrate() {
|
|
await connectDB();
|
|
|
|
try {
|
|
console.log('--- Starting Header Menu Migration ---');
|
|
|
|
// 1. Clear existing menu items
|
|
await HeaderMenu.deleteMany({});
|
|
console.log('🗑️ Cleared existing HeaderMenu collection');
|
|
|
|
// 2. Read JSON data
|
|
const dataPath = path.join(__dirname, '../data/header-menu.json');
|
|
const fileData = fs.readFileSync(dataPath, 'utf8');
|
|
const menuItems = JSON.parse(fileData);
|
|
|
|
// 3. Recursive import
|
|
await processMenuItems(menuItems);
|
|
|
|
console.log('--- Migration Completed Successfully ---');
|
|
process.exit(0);
|
|
} catch (error) {
|
|
console.error('❌ Migration Failed:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
migrate();
|