You need to enable JavaScript to run this app. Mongoose与Node.js按条件实现数组wage字段求和并传给Handlebars
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose与Node.js按条件实现数组wage字段求和并传给Handlebars

实现工资累加的修正方案

现有代码的常见问题

  • 字段名不匹配:原聚合查询的$match条件使用了错误的字段名name,与Schema定义的names不一致,查询取值误用req.body.name,与实际表单传参req.body.woker不对应
  • 数据类型不兼容:Schema中details数组内的wage字段为字符串类型,直接参与数值累加会出现字符串拼接、聚合返回0的问题
  • 模板取值错位:原模板中{{this.total}}位于循环嵌套外部,未从根上下文获取传递的总金额值,无法正常渲染
  • 渲染字段错位:原模板引用的chack、kooli字段未在Schema中定义,实际对应Schema里的sack、wage字段,会导致明细无法正常展示

后端逻辑修正

方案1:基于现有find查询逻辑改造(适配当前可运行的代码)

无需重写聚合逻辑,在原有查询流程中手动计算工资总和,代码改动量最小:

Person.find({
    names: req.body.woker
}).then(documents => {
    let totalWage = 0
    const usersDocuments = documents.map(doc => {
        // 遍历当前员工的所有明细,累加wage值
        doc.details.forEach(detail => {
            // 字符串转数值后累加,避免字符串拼接
            totalWage += Number(detail.wage)
        })
        return {
            details: doc.details
        }
    })

    res.render('employee/individuallist', {
        employeeName: req.body.woker,
        usersDocuments: usersDocuments,
        total: totalWage // 将总金额传入模板上下文
    })
}).catch(error => res.status(500).send(error))

方案2:修正Mongoose聚合写法

对原聚合管道的错误点逐一修正,适合需要在数据库端完成计算的场景:

Person.aggregate([
    // 按员工名过滤匹配的文档
    {
        "$match": {
            "names": req.body.woker
        }
    },
    {
        "$addFields": {
            "total": {
                "$sum": {
                    // 遍历details数组,逐元素做类型转换
                    "$map": {
                        "input": "$details",
                        "as": "detail",
                        "in": { "$toDouble": "$$detail.wage" }
                    }
                }
            }
        }
    }
]).then(personDocs => {
    // 单个员工查询仅取匹配的第一个文档
    const matchedPerson = personDocs[0] || {}
    res.render('employee/individuallist', {
        employeeName: req.body.woker,
        usersDocuments: [{
            details: matchedPerson.details || [],
        }],
        total: matchedPerson.total || 0
    })
}).catch(err => {
    console.log('查询错误:', err)
    res.status(500).send('系统异常')
})

Handlebars模板修正

调整字段引用与总金额取值位置,对齐实际Schema结构:

<table class="table table-striped" id="list">
    <thead>
        <tr>
            <th>日期</th>
            <th>卖家姓名</th>
            <th>麻袋数量</th>
            <th>工资金额</th>
        </tr>
    </thead>
    <tbody>
        {{#each usersDocuments}}
          {{#each this.details}}
            <tr>
                <td>{{this.date}}</td>
                <td>{{this.sellername}}</td>
                <td>{{this.sack}}</td>
                <td>{{this.wage}}</td>
            </tr>
          {{/each}}
        {{/each}}
                    
        <tr>
            <td colspan="3">总金额</td>
            <td>{{total}}</td>
        </tr>
    </tbody>
</table>

注意事项

  • 必须对字符串类型的wage做显式数值转换,否则会出现类似"210"+"210"="210210"的拼接错误
  • 跨文档的累加场景需要额外调整聚合的$group阶段逻辑,当前实现适配单员工查询的累加需求
  • 字段命名全程保持一致,避免因拼写错误导致查询、渲染失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 16:45:09