I’d like to pull guestAttends
from my event model and display the value for each individual event. Right now, the aggregation query is working but my page is only displaying the value from the FIRST event in the model and carrying it down the index, instead of populating each with its respective value.
How do I get it to display the event-specific value?
Here’s my function/route:
module.exports.showArtist = async (req, res,) => {
const artist = await Artist.findById(req.params.id).populate('events');
if (!artist) {
req.flash('error', 'Cannot find that Artist');
return res.redirect('/artists');
}
const artistId = artist._id;
let totalGuests = 0;
let attendedGuests = 0;
const eventData = await Event.aggregate([
{
"$match": {
"artist": artistId
}
},
{
$project: {
_id: 1,
name: 1,
guests: 1,
totalGuests: { $cond: { if: { $isArray: "$guests" }, then: { $size: "$guests" }, else: "NA" } },
attendedGuests: {
$size: {
$filter: {
input: "$guests",
as: "guest",
cond: {
$and: [{
$eq: ["$$guest.attended", "Y"]
}]
}
}
}
}
}
}
])
if (eventData && Array.isArray(eventData) && eventData.length > 0) {
totalGuests = eventData[0].totalGuests;
attendedGuests = eventData[0].attendedGuests;
}
const guestSignups = JSON.stringify(totalGuests);
const guestAttends = JSON.stringify(attendedGuests);
res.render('artists/show', { artist, guestSignups, guestAttends });
}
And here’s my page displaying the value:
<% for (let events of artist.events ) {%>
<div class="card mb-3 shadow">
<div class="row">
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title"><%= events.event_name %> </h5>
<p class="text"><%= events.description %> </p>
<p class="text"><%= events.eventData %> </p>
<p class="text">Guests signed up <%= guestSignups %> </p>
<p class="text">
<small class="text-muted"><%= events.description %> </small>
</p>
<a class="btn btn-primary" href="/events/<%= events.id %>">View Event</a>
</div>
</div>
</div>
</div>
<% }%>
Where am I going wrong?