Cannot read property 'substring' of undefined

Cannot read property 'substring' of undefined
0

#1

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:


#2

Sounds like blog.body doesn’t necessarily exist.


#3

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.


#4

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.


#5

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


#6

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


#7

@abheshekcr Thanks for your answer it worked