Pug prints the same value multiple times

Viewed 138

Here is my pug code:

html
  head
    style
        include ../../public/css/admin/admin.css
  body
    .main
      .yeniler-kutu
        each yeni, index in yeniler
          li(class="yeniler")= yeni 
    script
      include ../../public/js/admin/admin.js 

Here is my backend javascript code:

router.get("/index", async (req, res) =>
{
    try
    {
            const users = await User.find({});
            for(x=0; users[x]; x++)
            {
                if(users[x].gorev === "Menti" && !users[x].mentor)
                {
                    yenilerArr.push(users[x].name);
                }
            }
            res.status(200).send(pug.renderFile("./views/admin/admin.pug", 
            {
                yeniler: yenilerArr,
            })) 
    }
    catch(e)
    {
        res.status(400).send(e)
    }
})

The problem is pug is displaying the same list element multiple times. When I first load the page It works fine and only displays the strings once but when I reload the page I see the duplicate values. For example if yeniler array contains only one element called hello, it displays the string hello but when I reload the page I see 2 hellos. Thanks for reading.

2 Answers

I think little semantically mistake here:

for(x=0; users[x]; x++)

should be:

for(x=0; users.length; x++)

Looks like yenilerArr is defined outside the scope of the request handler, therefore it persists between requests, and acts like a global variable.

It should be defined inside request handler, somewhere before for loop:

const yenilerArr = []
Related