Node.js中如何按月份统计MySQL订单数量及reduce报错处理
问题根因
arr.reduce is not a function报错的核心原因是你赋值给arr的dataStore变量不是数组类型,常见触发场景:
- 未在当前函数作用域内初始化
dataStore为空白数组,要么引用了类型非数组的全局dataStore变量,要么之前的逻辑修改了dataStore的类型 - 数据库返回空数据时,后续逻辑异常导致
dataStore类型变更
同时你当前的日期key生成逻辑不符合需求,需要将默认的YYYY-MM格式转换为月份名-两位年份的格式。
修复实现方案
建议直接在Sequelize查询时给字段起别名,省去手动遍历替换字段前缀的步骤,同时在函数内部初始化数组避免全局污染,最终调整日期格式转换逻辑即可:
const dashboardOverview = async (req,res,next) => { // 定义月份全称映射数组 const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; // 查询时直接别名去掉od_前缀,省去后续循环替换 const ordersPerMonth = await Orders.findAll({ attributes: [ ['od_id', 'id'], ['od_created_date', 'created_date'] ] }); // 直接用查询结果处理,不需要额外的dataStore中间变量 const counts = ordersPerMonth.reduce((m, { created_date }) => { // 兼容字符串/Date类型的日期字段 const date = new Date(created_date); // 生成 月份名-两位年份 格式的key,比如January-21 const month = monthNames[date.getMonth()]; const year = date.getFullYear().toString().slice(-2); const key = `${month}-${year}`; return m.set(key, (m.get(key) ?? 0) + 1); }, new Map()); // 转换为普通对象,格式符合你的需求 const result = Object.fromEntries(counts); console.log(result); // 后续可以直接res.json(result)返回给前端 }
额外注意事项
- 如果你的
od_created_date字段存储的不是标准可被new Date()解析的格式,需要先自行调整为标准日期格式再做处理 - 若需要保持你原有遍历
dataStore的逻辑,只需要在函数第一行加上const dataStore = []初始化即可解决reduce报错问题
内容的提问来源于stack exchange,提问作者Nikeeta kurrey
相关产品推荐
相关产品推荐

