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.
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:
{ shorturl: '1axYBA5mB' }
{}
one
{
_id: 5fe4bba361430d00b4e7d73d,
original_url: 'cnn.com',
short_url: '1axYBA5mB',
__v: 0
}
two
cnn.com
three
{ shorturl: 'cnn.com' }
{}
one
null
two
(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/cnn.com. 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 cnn.com. But express’s res.redirect() redirects to a FQDN (http://...), relative to root (/admin), or finally relative to route (no slash, like cnn.com…). So your code worked on the supplied short url, redirected relative to the route since cnn.com had no leading slash (so to /api/shorturl/cnn.com), and then choked because there really was no record matching the short url cnn.com in the database.
So, the solution is to store a FQDN as the url in the database.