My URL shortener doesn't pass the third test

Here’s the code for the redirect endpoint. (Full index file at the bottom of the post)

// Shortener redirect endpoint.
app.get("/api/shorturl/:id", async (req, res) => {
  try {
    let urlToRedirect = "";
    let urlFound = false;
    let attempts = 0;
    while (!urlFound && attempts < 100) {
      console.log("Trying to find URL to redirect...");
      await linkModel.findOne({ shortenedID: req.params.id }, (error, data) => {
        if (error) console.log(error);
        // We need 2 seperate if statements because if the data is null
        // and we try to read the url value it will cause an exception.
        if (data !== null) {
          if (data.url !== "") {
            urlToRedirect = data.url;
            console.log("URL found:", data.url);
            urlFound = true;
          }
        }
        attempts++;
      });
    }
    console.log("Redirecting to:", urlToRedirect);
    res.redirect(urlToRedirect);
  } catch (error) {
    console.log("Exception Caught.");
    console.log(error);
  }
});

The reason I made it this way is because I noticed there was a delay between the link been saved in the database, so the redirect endpoint wouldn’t work immediately.

So i changed it to that and I tried it both locally and in codesandbox and the redirect works almost instantly now, which is great but for some reason in freecodecamp the test times out and I noticed something strange.

image

I used a new link, and as you can see it logs the link once and then it redirects to it when both if statements are executed and it works almost instantly.

But strangely when it does it with the freecodecamp test link, it saves just fine, but when it tries to redirect it gets stuck and doesn’t redirect to anything.
image

image

I have a added a 100 attempt cap so that this doesn’t go indefinitely. I’m not sure what’s wrong.

Here’s the full index file: index.js - Pastebin.com