Mongoose populate returning undefined on child-level docs despite the population working

Viewed 13

I'm using populate to reference my 'event' model across my 'qr' model--which appears to be working--but I'm running into an issue accessing the child attributes on the client side after the populate.

Qr model

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

const qrSchema = new Schema({
    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);

Controller function

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

In my console.log(qr) above, the event data comes through attached to the qr docs but when I run below iteration on the client side, I receive error Cannot read property 'event_name' of undefined (meaning event isn't coming through):

Client code

  <% for (let q of qr){%>
       <h5><%= q.event.event_name %></h5>
  <% } %>

Why isn't the population working on the client after coming through on the server (in my console log)?

0 Answers
Related