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://

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.


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.


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


@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?
app.get("/blogs", function(req, res){
“body” : {
$exists: true,
$ne : “”
// Blog.body.update(
// {$push: { body: NULL

        //     }});
}, function(err, blogs) {
      } else {
         res.render("index", {blogs: blogs}) 


Thank you for your answer it worked