首页 > 解决方案 > 在过滤函数中分配新的键和值对不起作用

问题描述

在我的节点服务器中,我有一个看起来像这样的过滤器功能

let totalHours = 0;
let laborCost = 0;
const employees = await Employees.findOne({
  company
});
const timeCards = await TimeCard.find({
  employee: employees.employees
}).populate("employee")
const filterTime = timeCards.filter(element => {
  let totalHoursByEmployee = 0;
  const times = element.times.filter(time => {
    if (time.job === jobId) {
      let hours = parseFloat(new Date(time.hours) / 3600000)
      totalHours += hours;
      totalHoursByEmployee += hours;
      laborCost += hours * time.hourlyRate;
    }
    return time.job === jobId;
  })
  element.totalHoursByEmployee = totalHoursByEmployee;
  element.times = times;
  return element.times.length !== 0;
})
res.json({
  times: filterTime,
  totalHours,
  laborCost
})

当我发回我的响应前端时,我的时间键是一个数组,但它在数组的任何索引中都不包含键 o totalHoursByEmployee。我知道过滤器不会改变数组,但我错过了什么。如果我在发送响应之前控制台日志filterTime[0].totalHoursByEmployee,那么正确的数字会显示在后端控制台上,但是当我在前端得到它时,找不到 totalHoursByEmployee 的键。

标签: javascriptnode.jsvue.js

解决方案


我想出了答案。这是因为我使用的是 Mongoose。所以当我运行查询时

const timeCards = await TimeCard.find({ employee: employees.employees }).populate("employee")

它返回一个 mongoose 对象,并且 mongoose 对象不允许您添加键,除非它们在 Schema 中定义。所以为了修复它我跑了

const timeCards = await TimeCard.find({ employee: employees.employees }).populate("employee").lean()

.lean() 返回一个 JSON 对象而不是 mongoose 对象,所以现在我可以向它添加键值对。


推荐阅读