我映射数组时为什么得到”undefined”?

huangapple go评论58阅读模式
英文:

Why am i getting undefined by mapping an array?

问题

我在我的控制器中有以下方法:

// @desc   创建游戏
// @route  POST /api/games/register
// @access Private

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

  // 验证小时是否有效且不重叠
  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: '小时范围重叠',
    });
  }

  // 验证员工是否存在
  employees.map((employee) => {
    const foundEmployee = Employee.findById(employee);
    console.log(foundEmployee);
    if (!foundEmployee) {
      return next(
        new ErrorResponse(`未找到id为${employee}的员工`, 404)
      );
    }

    if (foundEmployee.type !== 'manager') {
      return next(new ErrorResponse('员工必须是经理', 400));
    }
  });

  console.log(employees);

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

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

游戏包含一个名为"employees"的属性,它是一个包含员工ID的数组。我尝试映射员工数组,并尝试查找数组"employee"中的ID是否与我的Employees集合中的有效ID相匹配。

如果数组中的员工与有效员工ID不匹配,API应返回一个错误响应,其中包含消息"没有ID为${employee}的员工"。

但出于某种原因,我的控制台中打印出"undefined"。

英文:

I have the following method in my controller:

// @desc   Create a game
// @route  POST /api/games/register
// @access Private
exports.registerGame = asyncHandler(async (req, res, next) =&gt; {
const { name, description, employees, hours } = req.body;
// Verify that the hours are valid and dont overlap
const overlappingHours = hours.some((currentHour, currentIndex) =&gt; {
return hours.slice(currentIndex + 1).some((nextHour) =&gt; {
return (
(currentHour.opening &lt;= nextHour.opening &amp;&amp;
nextHour.opening &lt; currentHour.closing) ||
(currentHour.opening &lt; nextHour.closing &amp;&amp;
nextHour.closing &lt;= currentHour.closing) ||
(nextHour.opening &lt;= currentHour.opening &amp;&amp;
currentHour.closing &lt;= nextHour.closing)
);
});
});
if (overlappingHours) {
return res.status(400).json({
success: false,
error: &#39;Range of hours are overlapping&#39;,
});
}
// Verify that the employees exist
employees.map((employee) =&gt; {
const foundEmployee = Employee.findById(employee);
console.log(foundEmployee);
if (!foundEmployee) {
return next(
new ErrorResponse(`Employees not found with id of ${employee}`, 404)
);
}
if (foundEmployee.type !== &#39;manager&#39;) {
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,
});
});

A Game contains the employees property which is an array of ids that belong to employees.
I am trying to map the employees array and try to find if the id which is a string in the array employee is the same as a valid id of my Employees collection.

If the employees in the array do not match a valid employee id the api should return an error response with a message that says No employees with id ${employee}

But for some reason i am getting undefined in my console.

答案1

得分: 1

从数据库中在循环中获取员工不是一个好的解决方案,它会导致性能问题。

因此,您可以使用$in操作符一次性获取所有员工,并在代码中应用逻辑。

您可以像这样做:

    // 验证员工是否存在
    const foundEmployees = await Employee.find({
        _id: { $in: employees },
    });

    const foundEmployeesIds = foundEmployees.map((f) => f._id.toString());
    const errors = [];

    for (var i = 0; i < employees.length; i++) {
        if (!foundEmployeesIds.includes(employees[i])) {
            errors.push(`未找到ID为 ${employees[i]} 的员工`);
        } else {
            const emp = foundEmployees.find(
                (e) => e._id.toString() === employees[i]
            );

            if (emp.type !== 'manager') {
                errors.push(`员工不是经理 ${employees[i]}`);
            }
        }
    }

    if (errors.length > 0) {
        return next(new ErrorResponse(errors.join(','), 404));
    }
英文:

Getting the employees from db in a loop is not a good solution, it will have performance problems.

So instead you can get all the employees once using $in operator, and apply the logic in the code.

You can do something like this:

    // Verify that the employees exist
const foundEmploees = await Employee.find({
_id: { $in: employees },
});
const foundEmploeesIds = foundEmploees.map((f) =&gt; f._id.toString());
const errors = [];
for (var i = 0; i &lt; employees.length; i++) {
if (!foundEmploeesIds.includes(employees[i])) {
errors.push(`Employees not found with id of ${employees[i]}`);
} else {
const emp = foundEmploees.find(
(e) =&gt; e._id.toString() === employees[i]
);
if (emp.type !== &#39;manager&#39;) {
errors.push(`Employees is not manager ${employees[i]}`);
}
}
}
if (errors.length &gt; 0) {
return next(new ErrorResponse(errors.join(&#39;,&#39;), 404));
}

huangapple
  • 本文由 发表于 2023年6月19日 05:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定