Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoError: The $subtract accumulator is a unary operator

I can't seem to find any solutions for this problem. I just can't figure out what is wrong.

I already tried this Mongo subtract in group aggregation but no hope. The post also failed to explain further.

Here is my code:

 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,
    });
  });

it prompts MongoError: The $subtract accumulator is a unary operator everytime I query it.

like image 457
Kevz Avatar asked Apr 29 '18 15:04

Kevz


1 Answers

Change your query part to this one:

aggregateOptions = [
  {
     $match: {

     }
  },
  {
     $group: {
       _id: "$customerID",
       totalAmount: { $sum: "$amount" },
       totalpaidAmount: { $sum: "$paidAmount" }
     }
  },
  {
     $addFields:{
       totalAmountDue: { $subtract: ["$totalAmount", "$totalpaidAmount"] }
     }
  }
];
like image 64
Rahul Raj Avatar answered Oct 21 '22 15:10

Rahul Raj