Questions about code in Function

I have the following function:

exports = function () {
    const bases = ["02930919000100", "31599354000128", "31588482000176"];

    const promises = bases.map(async (value, index) => {
        const mongo = context.services.get("mongodb-atlas").db(value);
        return mongo.collection("vendas").aggregate([
            {
                $match: {
                    data: {
                        $gte: "2021-10-01",
                        $lte: "2021-10-29",
                    }
                }

            }
        ]); //Look at this line
    })

    return Promise.all(promises);
};

Your return is empty:

[{},{},{}]

But if I put “.toArray()” on the line I commented on in the code the return works.

exports = function () {
    const bases = ["02930919000100", "31599354000128", "31588482000176"];

    const promises = bases.map(async (value, index) => {
        const mongo = context.services.get("mongodb-atlas").db(value);
        return mongo.collection("vendas").aggregate([
            {
                $match: {
                    data: {
                        $gte: "2021-10-01",
                        $lte: "2021-10-29",
                    }
                }

            }
        ]).toArray(); //Look at this line
    })

    return Promise.all(promises);
};

Just putting the “.toArray()” works and the return is:

[[{“_id”:{“$oid”:“615b4b15bbe1278ebc65d8cf”},“id_vendas”:{“$numberInt”:“77588”}}],[{“_id”:{“$oid”:“615b7676bbe1278ebc6fe62e”},“id_vendas”:{“$numberInt”:“127454”}}],[{“_id”:{“$oid”:“615b2105bbe1278ebc5af4be”},“id_vendas”:{“$numberInt”:“61102”}}]]

Why? According to the documentation the return of aggregation are the query documents, I do not understand why I have to use the “toArray()” in this case.

1 Like