You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历员工ID数组时返回undefined的问题排查

问题解决:员工ID验证失败且控制台输出undefined

你的代码存在两个核心问题导致了当前现象:

  1. 未等待异步查询结果:Employee.findById(employee) 返回的是Promise对象,你没有用 await 获取实际查询结果,所以 foundEmployee 是一个处于pending状态的Promise,而非员工文档。此时判断 !foundEmployee 永远为false(Promise是真值),错误无法触发,控制台打印的也是Promise对象而非期望的员工数据或null。

  2. 用map处理异步操作无效:map 不会等待异步函数执行完成,代码会直接跳过验证步骤继续创建游戏,即使员工ID无效也能成功执行。

以下是修正后的完整代码:

// @desc   Create a game
// @route  POST /api/games/register
// @access Private

exports.registerGame = asyncHandler(async (req, res, next) => {
  const { name, description, employees, hours } = req.body;

  // Verify that the hours are valid and dont overlap
  const overlappingHours = hours.some((currentHour, currentIndex) => {
    return hours.slice(currentIndex + 1).some((nextHour) => {
      return (
        (currentHour.opening <= nextHour.opening &&
          nextHour.opening < currentHour.closing) ||
        (currentHour.opening < nextHour.closing &&
          nextHour.closing <= currentHour.closing) ||
        (nextHour.opening <= currentHour.opening &&
          currentHour.closing <= nextHour.closing)
      );
    });
  });

  if (overlappingHours) {
    return res.status(400).json({
      success: false,
      error: 'Range of hours are overlapping',
    });
  }

  // Verify that the employees exist and are managers
  for (const employeeId of employees) {
    const foundEmployee = await Employee.findById(employeeId);
    console.log(foundEmployee); // 现在会正确输出员工文档或null
    
    if (!foundEmployee) {
      return next(
        new ErrorResponse(`No employees with id ${employeeId}`, 404)
      );
    }

    if (foundEmployee.type !== 'manager') {
      return next(new ErrorResponse(`Employees must be managers`, 400));
    }
  }

  console.log(employees);

  const game = await Game.create({
    name,
    description,
    employees,
    hours,
  });

  res.status(201).json({
    success: true,
    data: game,
  });
});

修改说明:

  • 用 for...of 循环替代 map,确保逐个等待异步查询完成,验证不通过时立即终止流程返回错误。
  • 在 Employee.findById 前添加 await,获取实际的查询结果(员工文档或null)。
  • 修正错误提示文本为你需求的 No employees with id ${employeeId}。

内容的提问来源于stack exchange,提问作者tukitooo1998

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 14:35:22