遍历员工ID数组时返回undefined的问题排查
问题解决:员工ID验证失败且控制台输出undefined
你的代码存在两个核心问题导致了当前现象:
未等待异步查询结果:
Employee.findById(employee)返回的是Promise对象,你没有用await获取实际查询结果,所以foundEmployee是一个处于pending状态的Promise,而非员工文档。此时判断!foundEmployee永远为false(Promise是真值),错误无法触发,控制台打印的也是Promise对象而非期望的员工数据或null。用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
相关产品推荐
相关产品推荐

