【问题标题】:How to get percentage from one collection field and one collection populated field in MongoDB?如何从 MongoDB 中的一个集合字段和一个集合填充字段中获取百分比?
【发布时间】:2018-10-01 10:53:26
【问题描述】:

我有一个集合,其中一个字段带有数字,并且在该集合中填充了 ObjectId,其中还有一个带有数字的字段。看起来像这样:

{"_id":"5abe65e298002b2334bb1470","electoralUnit":"5ab906612f30fe23dc592591","turnoutByHour":"08:00","voterTurnout":10,"safeVoter":5,"__v":0}

{"_id":"5ab906612f30fe23dc592591","town":"5ab903952e9dc70408a81e32","name":"Something","__v":0,"electoralNumber":4200,"safeVoter":360}

我的路线是这样的:

router.get('/', (req, res) => {
  VoterTurnout.find({})
    .sort({turnoutByHour: 1})
    .populate('electoralUnit')
    .then(voterTurnouts => {
      ElectoralUnit.find({})
        .then(electoralUnits => {
                res.render('home/voterTurnouts/index', {
                  voterTurnouts: voterTurnouts,
                  electoralUnits: electoralUnits
              });
        });
    });
});

查看:

<tbody>
  {{#each voterTurnouts}}
    <tr data-row="{{electoralUnit.id}}">
      <th scope="row">{{turnoutByHour}}</th>
      <td>{{voterTurnout}} ({{Math.floor(voterTurnout * 100 / electoralUnit.electoralNumber)}}%)</td> // This doesn't working
      <td>{{safeVoter}}</td>
      <td><a href="/voterTurnouts/edit/{{id}}" class="btn btn-outline-info btn-sm">Izmeni</a></td>
    </tr>
  {{/each}}
</tbody>

我阅读了一些关于 mongodb 聚合的内容,但找不到可以帮助我解决此问题的示例...有什么帮助吗?

【问题讨论】:

  • 您希望百分比显示在 mongodb 或您的表格中?
  • 我需要在表中。
  • 你用什么来绘制表格?你是怎么做到的?我认为你应该在运行时计算 UI 上的百分比
  • 对不起,我在您阅读后编辑了文本。那里我已经有选民投票收集的数字,但没有选举数字。我认为我需要在路由中进行数学运算,然后将变量放在视图中。
  • 不要在路上做。您将需要处理所有文件。只需在 UI (HTML/js) 上执行。由于我们不知道您是如何填充表格的,因此我们无法说明您如何在那里进行填充。您想知道如何在路线中做到这一点吗?

标签: node.js express mongoose


【解决方案1】:

我用车把自定义助手完成了它。我用谷歌搜索thishandlebars 自定义助手并稍微编辑一下:

math: function(lvalue, operator, rvalue, options) {

    lvalue = parseFloat(lvalue);
    rvalue = parseFloat(rvalue);

    return {
        "+": lvalue + rvalue,
        "-": lvalue - rvalue,
        "*": lvalue * rvalue,
        "/": lvalue / rvalue,
        "%": Math.floor((lvalue / rvalue) * 100)
    }[operator];

}

然后导出数学值以查看并添加此车把:

{{math voterTurnout "%"electoralUnit.electoralNumber}}%

它正在工作。

【讨论】:

    猜你喜欢
    • 2014-09-16
    • 2020-04-30
    • 2021-09-11
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多