0

I have a two collection one is Category and the other is Blog while looping out the category, i want to get the numbers of post such category have in my Blog collection, using the category field in blog collection I was able to have this output on console with the code below, but how do I render it in ejs to have this result beneath?

Business 4

Sport 2

Religion 1

But how do I render it in ejs to look like this

I did this in my routes with the code below

app.get('/articles/play', async (req, res) => {
    const category = await catModel.find()
    category.forEach(async cat => {
        // console.log(cat.catname)
        const countIt = await blogModel.countDocuments({category: cat.catname})
        console.log(cat.catname, countIt)
    })

})
Harmless Guy
  • 13
  • 1
  • 5
  • Have no time to answer your question completely, but have a look at this question which demonstrates how to iterate with async functions: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – ofhouse Sep 28 '20 at 11:33

1 Answers1

0

Form a array of json where you push this data and pass this array to ejs to blindly render, like below

 app.get('/articles/play', async (req, res) => {
        const category = await catModel.find();
        const ejsArr = [];
        for(let i = 0; i < category.length; i++) {
            const countIt = await blogModel.countDocuments({category: category[i].catname});
            ejsArr.push({name:cat.catname, count:countIt});    
        }
        console.log(ejsArr)
        res.render('article', ejsArr);    
});
r7r
  • 1,440
  • 1
  • 11
  • 19
  • Please can you share light on how i will output the ejsArr in ejs templates? Thanks. – Harmless Guy Sep 28 '20 at 11:39
  • once this ejsArr is formed, in your ejs just loop through this array and use html css to design it, (or simply print it). (I assume you know ejs else refer this http://tanmaysarkar.com/array-with-ejs-template-in-nodejs/) – r7r Sep 28 '20 at 11:43
  • I loop through the ejsArr on my view and is showing empty, but when i console.log(ejsArr) i have this output [ { name: 'Business', count: 4 } ] [ { name: 'Business', count: 4 }, { name: 'Sport', count: 2 } ] [ { name: 'Business', count: 4 }, { name: 'Sport', count: 2 }, { name: 'Religion', count: 1 } ] – Harmless Guy Sep 28 '20 at 11:49
  • there is something wrong here, why your array has repeated values, are you have loops before sample code? – r7r Sep 28 '20 at 11:51
  • console log before res.render('article', ejsArr); and share that data – r7r Sep 28 '20 at 11:52
  • Console.log(ejsArr) return an empty array – Harmless Guy Sep 28 '20 at 11:56
  • from where did you got previous log then? – r7r Sep 28 '20 at 11:58
  • inside the loop – Harmless Guy Sep 28 '20 at 13:20
  • I have update answer with for loop, it was empty because it had async code and was not waiting for foreach to complete – r7r Sep 28 '20 at 13:28