I've created a Property controller :
//Retrieve Properties By Type
const getPropertiesByType = async (req: Request, res: Response) => {
const { cities, type } = req.query;
const citiesArr = typeof cities === 'string' ? cities.split(',') : [];
try {
const properties = await Promise.all(
citiesArr?.map((item) => {
return PropertyModel.aggregate([
{
$match: { city: item, propertyType: type },
},
{
$project: {
_id: 0,
city: 1,
country: 1,
cityPhoto: 1,
},
},
{
$group: {
_id: '$city',
country: { $first: '$country' },
totalProperties: { $sum: 1 },
cityPhoto: { $first: '$cityPhoto' },
},
},
]);
})
);
res.status(201).json(properties.flat());
} catch (error) {
console.log(error);
res.status(400).json(error);
}
}
When using Postman, the response I'm receiving looks like this :
[
{
"_id": "Davenport",
"country": "United States",
"totalProperties": 1,
"cityPhoto": "https://"
},
{
"_id": "Destin",
"country": "United States",
"totalProperties": 1,
"cityPhoto": "https://"
}
]
The issue I'm facing is that all objects are nested within arrays, but I would prefer to have them in a single main array. Is there a way to achieve this without using the aggregation pipeline?