0
votes

When I try to add new blog posts to my website I am continuously getting this error:

TypeError: C:\Users\shruti\Desktop\ejs-challenge\views\home.ejs:15 13|

14|       <p>

15|         <%= post.content.substr(0, 100) %>

16|         <a href="/posts/<%=post._id%>">Read More</a>

17|       </p>

18|       <% })%>

Cannot read property 'substr' of undefined at eval (eval at compile (C:\Users\shruti\Desktop\ejs-challenge\node_modules\ejs\lib\ejs.js:618:12), :22:39) at Array.forEach () at eval (eval at compile (C:\Users\shruti\Desktop\ejs-challenge\node_modules\ejs\lib\ejs.js:618:12), :16:14) at returnedFn (C:\Users\shruti\Desktop\ejs-challenge\node_modules\ejs\lib\ejs.js:653:17) at tryHandleCache (C:\Users\shruti\Desktop\ejs-challenge\node_modules\ejs\lib\ejs.js:251:36) at View.exports.renderFile [as engine] (C:\Users\shruti\Desktop\ejs-challenge\node_modules\ejs\lib\ejs.js:482:10) at View.render (C:\Users\shruti\Desktop\ejs-challenge\node_modules\express\lib\view.js:135:8) at tryRender (C:\Users\shruti\Desktop\ejs-challenge\node_modules\express\lib\application.js:640:10) at Function.render (C:\Users\shruti\Desktop\ejs-challenge\node_modules\express\lib\application.js:592:3) at ServerResponse.render (C:\Users\shruti\Desktop\ejs-challenge\node_modules\express\lib\response.js:1008:7) at C:\Users\shruti\Desktop\ejs-challenge\app.js:35:9 at C:\Users\shruti\Desktop\ejs-challenge\node_modules\mongoose\lib\model.js:4846:16 at C:\Users\shruti\Desktop\ejs-challenge\node_modules\mongoose\lib\model.js:4846:16 at C:\Users\shruti\Desktop\ejs-challenge\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16 at C:\Users\shruti\Desktop\ejs-challenge\node_modules\mongoose\lib\model.js:4869:21 at C:\Users\shruti\Desktop\ejs-challenge\node_modules\mongoose\lib\query.js:4397:11

home.ejs:

<%- include("partials/header") -%>

    <h1>HOME</h1>
    <p> <%= startingContent %> </p>

    <% console.log(posts); %>

    <div class="">
      <% posts.forEach(function(post){ %>
      <h1><%= post.title%></h1>

      <p>
        <%= post.content.substr(0, 100) %>
        <a href="/posts/<%=post._id%>">Read More</a>
      </p>
      <% })%>


        <form  action="/compose">
           <button class="btn btn-primary" type="compose" name="button">COMPOSE</button>
        </form>

    </div>


    <%- include("partials/footer") -%>
1

1 Answers

1
votes

The error message says that it "Cannot read property 'substr' of undefined", which means post.content is undefined inside your posts.forEach() loop. Try to log post and check its content.