javascript - MongoDB中的$subtract聚合操作导致页面不加载
问题描述
我对javascript很陌生。我正在尝试为网站创建仪表板。我希望仪表板显示有多少订单未完成。我能够显示已完成的订单,但是当我尝试使用 $subtract 通过从订单总数中减去已完成的数量来获取未完成的订单时,我的页面不再加载。我非常感谢有关此问题的任何帮助或指导。谢谢你。
我的未完成订单代码:
const unfullfilled = await Order.aggregate([
{
$group: {
_id: null,
fullfill: { $sum: '$shippedValue' },
orders: { $sum: 1 },
unfullfill: {$subtract:['$orders','$fullfill']},
},
},
]);
仪表板显示部分:
<li>
<div className="summary-title color2">
<span>
<i className="fa fa-shopping-cart" />Unfullfilled
</span>
</div>
<div className="summary-body">
{summary.unfullfilled[0] ? summary.unfullfilled[0].unfullfill : 0}
</div>
</li>
我的完整订单代码:
const fullfilled = await Order.aggregate([
{
$group: {
_id: null,
fullfill: { $sum: '$shippedValue' },
},
},
]);
仪表板显示部分:
<li>
<div className="summary-title color2">
<span>
<i className="fa fa-shopping-cart" />Fullfilled
</span>
</div>
<div className="summary-body">
{summary.fullfilled[0] ? summary.fullfilled[0].fullfill : 0}
</div>
</li>
解决方案
您不能使用$subtract
with $group
as $subtract
is not a accumulator 运算符。
你可以使用$project
舞台
const unfullfilled = await Order.aggregate([
{
$group: {
_id: null,
fullfill: { $sum: '$shippedValue' },
orders: { $sum: 1 }
},
},
{
$project:{
fullfill:1,
orders:1,
unfullfill: {$subtract:['$orders','$fullfill']}
}
}
]);
推荐阅读
- php - 没有for的PHP收益?
- ruby-on-rails - 来自守护程序的错误响应:没有这样的容器:
- python - 无法访问某些字典键
- javascript - 为什么 Javascript 类引用相同的构造函数?
- python - 连接到 ngrok 服务器的 python 套接字
- c++ - 如果类具有与类同名的成员,则生成构造函数
- node.js - 如何获取引用文档在 mongoosejs 中有一些字段的文档
- google-apps-script - 当变量在函数之外时,onOpen 菜单不起作用
- sql - 如何将 2 个 CTE 的查询缩短(替换)为 1 个 JOIN LATERAL
- jenkins-plugins - Bitbucket 构建状态通知程序 - 无法提取访问令牌