fetch the locations based on zone ANd city

master^2
Bhaskar 8 months ago
parent 1940117694
commit 586df75d02

@ -582,54 +582,63 @@ exports.addDepartment = async (request, reply) => {
// };
const getLocationsByCityAndZone = async (city, zone) => {
try {
const result = await City.aggregate([
{
$match: {
city: city, // Match documents with the same city
zone: zone, // Match documents with the same zone
},
},
{
$group: {
_id: { city: "$city", zone: "$zone" }, // Group by city and zone
locations: { $push: "$location" }, // Collect all location arrays
},
const getLocationsByCityAndZone = async (city, zone) => {
try {
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
}
},
{
$match: {
city: { $regex: `^${city.trim()}$`, $options: "i" }, // Trim & case-insensitive
zone: zone.trim() // Trim zone
}
},
{
$group: {
_id: { city: "$city", zone: "$zone" },
locations: { $push: "$location" },
},
{
$project: {
_id: 0, // Exclude the _id field
city: "$_id.city",
zone: "$_id.zone",
locations: {
$reduce: {
input: "$locations",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] }, // Flatten the location arrays
},
},
{
$project: {
_id: 0,
city: "$_id.city",
zone: "$_id.zone",
locations: {
$reduce: {
input: "$locations",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this"] },
},
},
},
]);
return result;
} catch (err) {
console.error(err);
throw new Error("Error fetching locations.");
}
};
},
]);
console.log("Query Result:", result); // Debugging output
return result;
} catch (err) {
console.error(err);
throw new Error("Error fetching locations.");
}
};
exports.getZonebasedLocations = async (req, reply) => {
try {
const { city, zone } = req.query;
console.log("Received City:", `"${city}"`, "Received Zone:", `"${zone}"`); // Debugging input
const locations = await getLocationsByCityAndZone(city.trim(), zone.trim());
reply.send({ status_code: 200, data: locations });
} catch (err) {
reply.status(500).send({ message: err.message });
}
};
exports.getZonebasedLocations = async (req, reply) => {
try {
const { city, zone } = req.query;
const locations = await getLocationsByCityAndZone(city, zone);
reply.send({ status_code: 200, data: locations });
} catch (err) {
reply.status(500).send({ message: err.message });
}
};
const getLocationsByZone = async (zone) => {
try {

Loading…
Cancel
Save