diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 7e7bc574..df2fe414 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -1117,42 +1117,43 @@ const getDepartmentsByName = async (officeName, city, departmentName) => { const getDepartmentNamesByCity = async (city) => { try { const trimmedCity = city.trim(); - + // Allow for extra whitespace before or after the city value in the database const query = { city: { $regex: `^\\s*${trimmedCity}\\s*$`, $options: "i" } }; console.log("MongoDB Query:", JSON.stringify(query, null, 2)); - + const result = await Deparments.find(query) .select("departmentName -_id") .lean(); - - return result.map(doc => doc.departmentName); + + // Remove duplicate department names + return [...new Set(result.map(doc => doc.departmentName))]; } catch (error) { console.error("Error fetching departments by city:", error); throw new Error("Error fetching departments by city."); } }; - -// API route handler -exports.getDepartmentsByCity = async (req, reply) => { - try { - const { city } = req.params; - if (!city || city.trim() === "") { - return reply.status(400).send({ message: "City is required." }); - } - - const departmentNames = await getDepartmentNamesByCity(city); - - if (departmentNames.length === 0) { - return reply.status(404).send({ message: "No departments found for the specified city." }); + // API route handler + exports.getDepartmentsByCity = async (req, reply) => { + try { + const { city } = req.params; + if (!city || city.trim() === "") { + return reply.status(400).send({ message: "City is required." }); + } + + const departmentNames = await getDepartmentNamesByCity(city); + + if (departmentNames.length === 0) { + return reply.status(404).send({ message: "No departments found for the specified city." }); + } + + reply.send({ status_code: 200, data: departmentNames }); + } catch (error) { + console.error("API Error:", error); + reply.status(500).send({ message: error.message }); } - - reply.send({ status_code: 200, data: departmentNames }); - } catch (error) { - console.error("API Error:", error); - reply.status(500).send({ message: error.message }); - } -}; + }; +