Unhandled 'error' event on FindOne in URL Shortener Microservice

I am trying to do the URL Shortener Microservice project.

I entered https://www.freecodecamp.org into the Input and pressed the Post URL button

I cannot work out why I get the following appearing in my console:

 npm start

> shorturl@0.0.3 start
> node index.js

Listening on port 3000
https://www.freecodecamp.org
VALID
node:events:505
      throw er; // Unhandled 'error' event
      ^

Here is the code that I am running:

app.post('/api/shorturl', function(req, res) {
  const passedUrl = req.body.url;
  console.log(passedUrl);
  //based on isValidHttpUrl is from Pavlo (stackoverflow) Apr 18, 2017 at 8:22
  function isValidUrl(string) {
    let url;
    try {
      url = new URL(string);
    } catch (_) {
      return false;  
    }
    return (url.protocol === "http:" || url.protocol === "https:") && url.hostname.substr(0, 4) === "www." && url.hostname.substr(0, 4) === "www." && url.protocol + '//' + url.hostname === string;
  }
  if (isValidUrl(passedUrl)) {
    console.log("VALID");
    //Check if URL already in database
    urlShort.findOne({ URL: passedUrl }, function (err, urlShort) {
      if (err) throw err;
        console.log(`Store url in database:${urlShort.URL}:`);
    });
  }
  else {
    res.json({ error: 'invalid url' });
  }
});

Regards
Alan

Thank you for replying - here is my link:
https://replit.com/@AlanBra/boilerplate-project-urlshortener#index.js

console.log(`Store url in database:${urlShort.URL}:`);

This line is causing the error. You try to reference urlShort.URL but urlShort is null, and null values do not have properties. It is null because if the url is not in the database yet, the second argument passed to the callback function of findOne will be null.

On another note, I would not name the 2nd argument urlShort to avoid confusion with the global urlShort that is the model.

Thank you so much for replying - so obvious once you pointed it out! :slightly_smiling_face:

I also take your point about avoiding confusion with variable names - thank you for that.