Cannot read property 'substring' of undefined

Hi, I’m doing some coding using nodejs, mongoose.

This is the file I’m working as :slight_smile: ttps://github.com/HyperSprite/web-developer-bootcamp/blob/master/blog/views/index.ejs

At Line 19

<%- blog.body.substring(0, 100) %>

the substring causes the error:

TypeError: /home/ubuntu/workspace/RESTful Routing/RESTfulBlogApp/views/partials/header.ejs:18

Cannot read property ‘substring’ of undefined
at eval (eval at (/home/ubuntu/workspace/RESTful Routing/RESTfulBlogApp/node_modules/ejs/lib/ejs.js:485:12), :33:25)
at Array.forEach (native)
at eval (eval at (/home/ubuntu/workspace/RESTful Routing/RESTfulBlogApp/node_modules/ejs/lib/ejs.js:485:12), :19:14)
at returnedFn (/home/ubuntu/workspace/RESTful Routing/RESTfulBlogApp/node_modules/ejs/lib/ejs.js:514:17)

Not sure why this is so. I appreciate if someone could assist me and explain why applying the substring would turn out undefine error. When I remove the substring, it is fine.

:slight_smile:

Sounds like blog.body doesn’t necessarily exist.

Thanks for the reply. I needed the blog.body to look at the description of the blog.

I have tried without the substring and it work but not with it.

Have a good weekend.

Thanks.

Right but it sounds like you need to check that blog.body exists before you try to get the substring. Try putting in a check that blog has the property body. Take the substring if you can, otherwise do whatever logic.

I’ve got same error. It doesn’t still work. If you have solution , let me know

in one of your posts you may have left body empty…so it pops out an error …clear the database and try by adding single post and applying subsring property …hope this helps

2 Likes

@abheshekcr Thanks for your answer it worked

1 Like

So i had the same error and found that for whatever reason there was an empty “body” field in the DB from one of my posts. I was trying to see if i could find a way to check for this and then update that field with something like “Field is Null or Empty”. In my app.js i put this with is the first part of the check. I was thinking that maybe a foreach would be better. I am stuck on the updating or assigning a variable to the missing db.
Anyone have any suggestions?
//INDEX ROUTE
app.get("/blogs", function(req, res){
if(Blog.find({
“body” : {
$exists: true,
$ne : “”
}
// Blog.body.update(
// {$push: { body: NULL

        //     }});
}, function(err, blogs) {
      if(err){
       console.log("ERROR!"); 
       
      } else {
         res.render("index", {blogs: blogs}) 
      }
}));

});

Thank you for your answer it worked