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
      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;
  //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)) {
    //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' });


Please post a link to your entire project code. Thank you.

Thank you for replying - here is my link:

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.