Ejs output parent.child is not iterable

Viewed 17

I'm trying to iterate over 'redirect' subdocuments from my qr model but am receiving the type error qr.redirect is not iterable. The iteration is setup on the client side in my ejs template:

EJS render

<% for (let q of qr.redirect) {%>
    <h1><%= q.name %> </h1>
<% } %>

Controller function

module.exports.showActivations = async (req, res) => {
    const qr = await Qr.find({ user: user._id });
    res.render('users/activations', { qr });
};

qr.js model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const qrSchema = new Schema({
    redirect: [{
        name: String,
        url: String,
        qrcode: String,
    }],
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    event: {
        type: Schema.Types.ObjectId,
        ref: 'Event'
    },
});

module.exports = mongoose.model('Qr', qrSchema);

What's interesting is if I run console.log(qr) in the controller function, the redirect subdocuments are logged as [ [Object] ] but if I run console.log(qr[1]) (for example) the entire document and subdocuments key:value pairs are logged.

Not sure if the above idiosyncrasy has anything to do with my client side error but would love some help on how to fix my client side for loop.

1 Answers

First of all, make sure qr.redirect has a length greater than zero in the if condition. Then apply forEach loop on the list.

<% if(qr.redirect.length){ %>
    <% qr.redirect.forEach(user=> %>
       <%= user.name %>
     <% })  %>
<% }%>
Related