MongoError:$ subtract累加器是一元运算符

时间:2018-04-29 15:59:22

标签: mongodb mongoose

我似乎无法找到解决此问题的任何方法。我无法弄清楚出了什么问题。

我已经尝试了这个Mongo subtract in group aggregation,但没有希望。这篇文章也未能进一步解释。

这是我的代码:

 var aggregateOptions;
  aggregateOptions = [{
    $match: {

    }
  },{
    $group: {
      _id: "$customerID",
      totalAmount: { $sum: "$amount" },
      totalpaidAmount: { $sum: "$paidAmount" },
      totalAmountDue: { $subtract: ["$totalAmount", "totalpaidAmount"] }
    }
  }];

  Sale.sales.get(Sale.Schema, aggregateOptions, (err, saleRecord) => {
    if (err) throw err;
    console.log(saleRecord);

    res.json({
      pageTitle: "Customer List",
      currentUser: req.user,
      saleRecord: saleRecord,
    });
  });

它提示MongoError:每次查询时,$ subtract累加器都是一元运算符。

1 个答案:

答案 0 :(得分:8)

将您的查询部分更改为此部分:

aggregateOptions = [{
$match: {

}
},{
$group: {
  _id: "$customerID",
  totalAmount: { $sum: "$amount" },
  totalpaidAmount: { $sum: "$paidAmount" }
 },
 $addFields:{
   totalAmountDue: { $subtract: ["$totalAmount", "$totalpaidAmount"] }
 }
}];