From 2cf3a536029776b0051ec749d5a9144c67e447b1 Mon Sep 17 00:00:00 2001 From: Bhaskar Date: Fri, 31 Jan 2025 12:49:58 +0530 Subject: [PATCH] changes --- src/controllers/departmentController.js | 43 +++++++++++++++++++------ 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/src/controllers/departmentController.js b/src/controllers/departmentController.js index 9a4489fe..14df550a 100644 --- a/src/controllers/departmentController.js +++ b/src/controllers/departmentController.js @@ -587,16 +587,16 @@ const getLocationsByCityAndZone = async (city, zone) => { const result = await City.aggregate([ { $project: { - city: { $trim: { input: "$city" } }, // Trim city field in DB - zone: { $trim: { input: "$zone" } }, // Trim zone field in DB - location: 1 - } + city: { $toLower: { $trim: { input: "$city" } } }, // Normalize city name (lowercase & trim) + zone: { $trim: { input: "$zone" } }, // Trim zone field + location: 1, + }, }, { $match: { - city: { $regex: `^${city.trim()}$`, $options: "i" }, // Trim & case-insensitive - zone: zone.trim() // Trim zone - } + city: { $regex: `^${city.trim().toLowerCase()}$`, $options: "i" }, // Case-insensitive & trimmed + zone: zone.trim(), + }, }, { $group: { @@ -613,7 +613,27 @@ const getLocationsByCityAndZone = async (city, zone) => { $reduce: { input: "$locations", initialValue: [], - in: { $concatArrays: ["$$value", "$$this"] }, + in: { $concatArrays: ["$$value", "$$this"] }, // Flatten nested arrays + }, + }, + }, + }, + { + $group: { + _id: { city: "$city", zone: "$zone" }, // Merge all data into a single object + locations: { $push: "$locations" }, // Collect all locations + }, + }, + { + $project: { + _id: 0, + city: "$_id.city", + zone: "$_id.zone", + locations: { + $reduce: { + input: "$locations", + initialValue: [], + in: { $concatArrays: ["$$value", "$$this"] }, // Flatten again after merging }, }, }, @@ -621,7 +641,7 @@ const getLocationsByCityAndZone = async (city, zone) => { ]); console.log("Query Result:", result); // Debugging output - return result; + return result.length ? result[0] : null; // Return a single object instead of an array } catch (err) { console.error(err); throw new Error("Error fetching locations."); @@ -633,6 +653,11 @@ exports.getZonebasedLocations = async (req, reply) => { const { city, zone } = req.query; console.log("Received City:", `"${city}"`, "Received Zone:", `"${zone}"`); // Debugging input const locations = await getLocationsByCityAndZone(city.trim(), zone.trim()); + + if (!locations) { + return reply.send({ status_code: 404, message: "No data found." }); + } + reply.send({ status_code: 200, data: locations }); } catch (err) { reply.status(500).send({ message: err.message });