Using Each Loop in EJS Template and Express JS

I am working on a form validation and i am trying to loop the errors in my template but i keep getting error.

In my posts routes i have this'/create',  async (req, res)=>{
        var errors = [];

            errors.push({message: 'Please Add a Title'})

        if(errors.length > 0){
            res.render('admin/posts/create',{errors: errors})
        } else{


    let filename = 'Nissan.jpeg';

        const file =  req.files.file
         filename = + '-' +'./public/uploads/' + filename, (err)=>{
            if(err) throw err


    let allowComments = true;


        allowComments = true;

    }  else{

        allowComments = false;
    const newPost = await new Post({
        title: req.body.title,
        status: req.body.status,
        allowComments: allowComments,
        body: req.body.body,
        file: filename
    const savedPost =  await;
    // console.log(savedPost);
    } catch (error){


And in my ejs template with url (admin/posts/create) i have this

<% errors.forEach(errors => { %>
 <%-errors.message %>
<% }) %>

But i keep getting this error message in my browser

ReferenceError: /blog/views/admin/posts/create.ejs:2
    1| <%- include('../admin-partials/head')  %> 
 >> 2| <% errors.forEach(error => { %> <%-error.message %> <% }) %>
    3| <div class="dashboard-col-2">
    4|     <h1>Create Post</h1>

errors is not defined

What can i do to solve this error message?

When i do console.log(errors) i get this

[{ message: 'Please Add a Title' } ]

You can read this thread and focus on the second answer: node.js - ejs template variable is not defined on page load and errors - Stack Overflow

I am still getting the ```|

Create Post

8| <% if (errors) { %>

  • <%= error.message %>

  • 10| <% } %>

    errors is not defined

    As you use try catch block when the code in the try fail then the code in the catch work so for test add the render function with (errors) in the catch block and in the try block use throw

    @Mohamed-Magdey i really do not understand this sentence

    try to put that res.render('admin/posts/create',{errors: errors}) in catch block and tell me if it works

    @Mohamed-Magdey Anytime i refresh the page it self i still get errors undefined. I am new to express js and ejs. Hence why i am finding it difficult to solve

    No problem it’s normal. can you please share your code in github or glitch and you can use this until i see the code error?.message

    @Mohamed-Magdey here is the glitch Glitch :・゚✧

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