Url shortener service - app crashes while trying to access the model

Tell us what’s happening:
It is the first challenge I try to complete on my own with Mongoose.
I can’t find the reason why the app crashes every time I try to access the Url model in my database.
It always claims that it tries to access properties of null!
Part of the log:

My code so far:
boilerplate-project-urlshortener-1 - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36

Challenge: URL Shortener Microservice

Link to the challenge:

Just follow the error message. It’s telling you it can’t read a property short_url of an object and there is only one place such a call is made:

app.post('/api/shorturl', bodyParser.urlencoded({extended: false}),(req, res)=>{
  const fullUrl = req.body.url;
  let shortUrl = 1;
  Url.findOne({})  // This is not the find you are looking for.
      .exec((error, result)=>{
        if (!error && result !== undefined) {
          // Here's the problem.  Log some stuff here.
          shortUrl = result.short_url + 1;

What happens with shortUrl if you are creating the first record and result is empty (empty is not undefined)? Read this to see what happens when you send an empty object to findOne().

Also please post errors (code, etc.) as code blocks. Much more useful than an image. Posting the repl.it was very helpful.

So simple to fix.
You’re right I just had to replace “result !== undefined” by “result !== null”.

Also thanks for your recommendations. Will take them into consideration in the future.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.