Site works in dev mode but not in deployment preview

I have a project that works fine when I use netlify dev but when I netlify deploy it, it does not work properly and it gives me these errors:

(index):10 GET https://6305c17d2c62033bdf60a6b6--mango-database-0.netlify.app/.netlify/functions/get_movies 502
(index):10 = let results = await fetch("/.netlify/functions/get_movies").then((response) => response.json());

(index):17 TypeError: results.forEach is not a function
results.forEach((result) => {
  const listItem = document.createElement("li");
  listItem.innerText = result.title;
  document.getElementById("movies").appendChild(listItem);
});

I think the second error is due to the first and anyway this is the get_movies function

const { MongoClient } = require("mongodb");
require("dotenv").config();
const mongoClient = new MongoClient(process.env.MONGODB_URI);
const clientPromise = mongoClient.connect();
const handler = async (event) => {
  try {
    const database = (await clientPromise).db(process.env.MONGODB_DATABASE);
    const collection = database.collection(process.env.MONGODB_COLLECTION);
    const results = await collection.find({}).limit(10).toArray();
    return {
      statusCode: 200,
      body: JSON.stringify(results),
    };
  } catch (error) {
    return { statusCode: 500, body: error.toString() };
  }
};
module.exports = { handler };

And I already added the .env variables in Netlify

Sometimes, I dont get an error at index:10 but at get_movies:1, so I guess the problem is requiring mongodb, what do I have to do?

Hey @lko3001

The get_movies function is timing out as it is taking longer than 10seconds.

@coelmay do you know how can I fix it? All I did is following this tutorial

Not having used MongoDB I cannot say for sure, but it is possible the amount of data returned from the await collection.find({}).limit(10).toArray(); is too big, or taking too long.

I dont think that’s the problem because in dev mode it loads almost immediately and anyway they are just 3 really short JSONs

Again, not having used MongoDB (and not knowing anything about the data retrieved), I was only taking a stab.

Hey @lko3001,

This site appears to be renamed/deleted. Are you still having issues?