Skip to content

Server data coming through as [Object object] on client

enter image description here

I’m trying to display my data being sent from the server but it’s not coming through properly (see [Object object] in the bottom left of the image above). Here’s the client side code:

        <div class="card-body">
          <h5 class="card-title"><%= event.event_name %></h5>
          <p class="card-text"><%= event.description %></p>
          <p class="card-text"><%= eventData %></p>
        </div>

The server is sending the data in an array in below format:

 const eventData = [{
      _id: 'objectId_for_the_event',
      guests: [
          'guestId1',
          'guestId2', 
          'guestId3',
          'guestId4',
          'guestId5'
       ],
       totalGuests: 5,
       attendedGuests: 0
      }
     ]

I want the values from totalGuests and attendedGuests to display on the client. Here’s my function in the server (it’s long and a little confusing but that console.log in the last line works perfectly, so the variables are working):

module.exports.showEvent = async (req, res) => {
    const event = await Event.findById(req.params.id).populate('artist');
    const { guest_id } = req.cookies;
    let totalGuests = 0;
    let attendedGuests = 0;
    const eventData = await Event.aggregate([
        {
            "$match": {
                "_id": objectId(req.params.id)
            }
        },
        {
            $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;
    }
    if (!event) {
        req.flash('error', 'Cannot find that Event');
        return res.redirect('/events');
    }
    res.render('events/show', { event, eventData });
    console.log(totalGuests, attendedGuests);
};

How do I get those two variables out of the array and onto the client?

Answer

You need to use JSON.stringify() to stringify the values before sending them. It would be something like this:

JSON.stringify(attendedGuests);