Search code examples
javascriptnode.jsasynchronousasync-awaitprisma

How to push to external array from within a Prisma await async function


I'm trying to push an array to an external array that is called buildings from within a lodash foreach loop in a async await Prisma.io request.

const buildings = [];
const companies = await prisma.user.findMany({
  where: {
    maintainers: {
      some: {
        id: req.user.id,
      },
    },
  },
});

console.log(companies);

_.forEach(companies, async (c) => {
  const edifici = await prisma.building.findMany({
    where: {
      TU: {
        some: {
          TU: {
            id: c.id,
          },
        },
      },
    },
  });


  console.log(edifici);

  buildings.push(...edifici);
});

console.log(buildings);

the result of the fist log console.log(companies) do log the companies needed. the result of the second log console.log(edifici) do log the buildings that belongs to che companies in the for loop.

However when I try to push the result of the edifici await request into the buildings array which has been declared outside the foor loop the log does return an empty array.

How to push the result of the await request into the buildings array?


Solution

  • I've found a workaround to find out all buildings belonging to UU users via prisma:

    const buildings = await prisma.building.findMany({
      where: {
        TU: {
          some: {
            TU: {
              maintainers: {
                some: {
                  id: req.user.id,
                },
              },
            },
          },
        },
      },
    });