/** * Sync HeaderMenu children of the "Services" menu item * to match the current list of services in the database. * * Strategy: * - Find the HeaderMenu item whose url === '/services' * - Delete all its direct children * - Re-create one child per service item (url = /services/) */ const HeaderMenu = require("../models/headerMenu"); const slugify = require("slugify"); /** * @param {Array} serviceItems - array of service objects { slug, name } */ const syncServiceMenu = async (serviceItems = []) => { try { // 1. Find the "Services" parent menu item const servicesParent = await HeaderMenu.findOne({ url: "/services" }); if (!servicesParent) { console.warn("[syncServiceMenu] No HeaderMenu item with url=/services found. Skipping sync."); return; } const parentId = servicesParent._id; // 2. Remove all existing children of that parent await HeaderMenu.deleteMany({ parentId }); // 3. Re-create one child per service const ops = serviceItems .filter((s) => s && s.slug && s.name) .map((s, index) => ({ title: s.name, slug: slugify(s.name, { lower: true, strict: true }), url: `/services/details/${s.slug}`, parentId, order: index + 1, status: "active", type: "internal", is_maintainance: false, })); if (ops.length > 0) { await HeaderMenu.insertMany(ops); } console.log(`[syncServiceMenu] Synced ${ops.length} service menu items under parentId=${parentId}`); } catch (err) { // Non-fatal – log but don't crash the main request console.error("[syncServiceMenu] Error syncing service menu:", err.message); } }; module.exports = syncServiceMenu;