Home > other >  Mongodb aggregation response
Mongodb aggregation response

Time:10-03

I have a Property controller :

//Get Properties By Type
const getPropertiesByType = async (req: Request, res: Response) => {
    const { cities, type } = req.query
    const citiesArr = typeof cities === 'string' ? cities.split(',') : []
    try {
        const property = 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(property)
    } catch (error) {
        console.log(error)
        res.status(400).json(error)
    }
} 

in Postman i am getting this reponse :

[
    [
        {
            "_id": "Davenport",
            "country": "United States",
            "totalProperties": 1,
            "cityPhoto": "https://"
        }
    ],
    [
        {
            "_id": "Destin",
            "country": "United States",
            "totalProperties": 1,
            "cityPhoto": "https://"
        }
    ],
] 

Problem is, that i get all objects in arrays, but i want instead get in response all objects in one main array. Also, can i do that without aggregation pipeline?

CodePudding user response:

You can use array.flatMap() once you receive aggregation result:

const property = [
    [
        {
            "_id": "Davenport",
            "country": "United States",
            "totalProperties": 1,
            "cityPhoto": "https://"
        }
    ],
    [
        {
            "_id": "Destin",
            "country": "United States",
            "totalProperties": 1,
            "cityPhoto": "https://"
        }
    ],
] ; // your aggregation output

const response = property.flatMap(x => x);
console.log(response);

The reason you can't do it directly in aggregation pipeline is you are using Promise.all which returns an array and each .aggregate() also returns an array so you will get an array of arrays anyway.

  • Related