Ramzan Rozali
Ramzan Rozali

Reputation: 53

Meteor ReactiveAggregate

I want to create meteor reactive aggregation for Transactions collection.

The transactions has date, so i want to aggregate data by month.

The code is:

ReactiveAggregate(this, Transactions, [
    {
      $match: {
        'date': {
          $gte: new Date(startDate),
          $lt: new Date(endDate)
        }
      }
    },
    {
      '$group' :
      {
        '_id' : { month: { $month: "$date" }},
        'totalProfit': { $sum: "$totalProfit"},
        'totalSales': { $sum: "$totalSales" },
        'totalExpenses': { $sum: "$totalExpenses" },
        count: { $sum: 1 }
      }
    },
    {
      '$project':{
        date: '$date',
        totalProfit: '$totalProfit',
        totalSales: '$totalSales',
        totalExpenses: '$totalExpenses',
      }
    }
  ], { clientCollection: "report3MonthsTransactions" });

});

When i do this, it will prompt error:

Error: Meteor does not currently support objects other than ObjectID as ids

Thanks!

Upvotes: 5

Views: 303

Answers (1)

MasterAM
MasterAM

Reputation: 16478

Your $group clause is:

'$group' : {
  '_id' : { month: { $month: "$date" }},
  ...
}

which results in each document having a composite _id: {_id: {month: <someMonth>}, ...}, where each _id is an object that is indeed not an ObjectID.

In your case, having {_id: <someMonth>, ...} would suffice.

This can be achieved by grouping it as follows:

'$group' : {
  '_id' : { $month: "$date" },
  ...
}

By the way, if you need to have the _id as a string (and I think you do), you can use $substr to convert it:

'$group' : {
  _id: {$substr: [{$month: '$date'}, 0, 2]},
  ...
}

Upvotes: 2

Related Questions