Looping through mongoDB queries and arrays in ejs

I have an ejs file that creates a table for all the users in my mongodb. Right now the ejs file simply creates 1 row for every user in my database. What I need it to do instead is create several rows for each user based on how many bullets they have. Each User has a bullets property, and the query is only pulling users that have bullets.

So if Johnny Cash had 5 Bullets instead of creating just one new row for Johnny Cash, it would create 5 new table rows for him. Ideally, these rows would be labled Johnny Cash (1), Johnny Cash (2), Johnny Cash (3), and so on.

dashboard.js

<%- include('partials/header'); %>
<a href="/api/users/logout" class="btn btn-secondary">Logout</a>
<a href="/api/users/buyBullet" class="btn btn-warning">Buy Bullet</a>
<div class="container">
  <div class="col-md-6 m-auto">
    <div class="card card-body">
      <h1 class="text-center mb-3">Dashboard</h1>
      <p>There is a total of <%= users.length %> users with a total of <%= bullets %> bullets</p>
      <p>The Date is now
        <b><%= new Intl.DateTimeFormat('en-GB', { year: 'numeric', month: 'long', day: '2-digit'}).format(new Date()) %></b>
        and the time is now <b><%= new Date().toLocaleTimeString() %></b></p>
    </div>
  </div>

  <div class="mt-5 mb-5">
      <% users.forEach(function(user){ %>
        <% user.bullets.forEach(function(user2){ %>
          <p><%= user2.name %></p>
        <% }); %>
      <% }); %>
  </div>

  
  
</div>

indexRouter.js (this is where the users object is defined)

const express = require('express');
const router = express.Router();
const User = require('../user/userModel');
const { ensureAuthenticated } = require('../../config/auth');
const _ = require('lodash');


router.get('/dashboard', ensureAuthenticated, async (req, res, next) => {
  const users = await User.find({ bullets: { $gt: 0 } });
  let bulletsArr = [];

  users.forEach(user => {
   bulletsArr.push(user.bullets);
  })

  const bullets = _.sum(bulletsArr);

  res.render('dashboard', {
    users,
    bullets
  });
});

module.exports = router;

You can also check the repo!

Github REPO

29 thoughts on “Looping through mongoDB queries and arrays in ejs”

Leave a Comment