服务器数据作为客户端上的 [Object object]

Server data coming through as [Object object] on client

我正在尝试显示从服务器发送的数据,但它没有正确通过(请参阅上图左下角的 [Object object])。这是客户端代码:

        <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>

服务器正在按以下格式发送数组中的数据:

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

想要 totalGuests 和 attendedGuests 的值显示在客户端上。这是我在服务器中的函数(它很长而且有点令人困惑,但最后一行中的 console.log 完美运行,因此变量正在运行):

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);
};

如何将数组的这两个变量 out 传送到客户端?

尝试传递数组中的第一个对象而不是数组本身:

res.render('events/show', { event, eventData[0] });.

您也可以像 const [{totalGuests, attendedGuests}] = eventData; 一样解构它,然后将这两个变量作为 totalGuestsattendedGuests

发送

您需要在发送之前使用 JSON.stringify() 对值进行字符串化。应该是这样的:

JSON.stringify(attendedGuests);