Can't read property of null (urlshortener)

Tell us what’s happening:

I keep getting an error that the program can’t read original_url property of “null” which insinuates that my findOne() function is returning null. The problem is, its returning null when there is a match. The strange part is that sometimes it does work right, but when it does it isn’t because I changed something.

Your code so far

Link to repl!

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36.

Challenge: URL Shortener Microservice

Link to the challenge:

If you show some code someone might be able to help. Like your findOne and maybe how you are saving the url in the database.

If you are using MongoDB Atlas you can just log in and see what is in your database and if the data is what you expect it to be.

Added a link to my repl above, for some reason it wasn’t showing up right, sorry about that! I’ve checked the atlas and it showed up as expected. and yet the error suggests that I’m not finding any records.
My get request (which includes the find one ) is as follows:

  URL.findOne({short_url: req.params.shorturl})

I found the problem, and the answer is in the documentation. I really should have looked there first.

First, I added some stuff to your route:

app.get('/api/shorturl/:shorturl', (req,res)=>{
  URL.findOne({short_url: req.params.shorturl})
  .then((url) => {
    return res.redirect(url.original_url)
    // return res.redirect(`http://www.${url.original_url}/`);

and got the following output

{ shorturl: '1axYBA5mB' }
  _id: 5fe4bba361430d00b4e7d73d,
  original_url: '',
  short_url: '1axYBA5mB',
  __v: 0
{ shorturl: '' }
(node:5208) UnhandledPromiseRejectionWarning:...

which means the code was working, and then went through the route again (why?). I finally noticed that when I stopped the server, my browser’s url bar contained /api/shorturl/ When I swapped the last two lines of the code above, it worked.

What was happening, was your redirection code was working and redirected to But express’s res.redirect() redirects to a FQDN (http://...), relative to root (/admin), or finally relative to route (no slash, like…). So your code worked on the supplied short url, redirected relative to the route since had no leading slash (so to /api/shorturl/, and then choked because there really was no record matching the short url in the database.

So, the solution is to store a FQDN as the url in the database.

1 Like