Hello everyone, currently I am trying around with aggregation. Surely I will join the aggregation course, but I have to fullfill my exercise first. I have build a webshop and want to get the income out of my orders-collection. I matched the field createdAt with month and that is working. But I want to get the income of the day and the full year either. Now I am getting the error:
MongoServerError: Invalid $project :: caused by :: Unknown expression $day
Code:
orderRouter.get('/income', verifyTokenAndAdmin, async (req:Request, res:Response)=>{
const date = new Date();
const lastDay = new Date(date.setDate(date.getDate()-1));
const year = new Date().getFullYear();
const lastMonth = new Date(date.setMonth(date.getMonth()-1));
const previousMonth = new Date(new Date().setMonth(lastMonth.getMonth()-1));
try{
const income = await Order.aggregate([
{$match:{createdAt:{$gte: previousMonth}}},
{$match:{createdAt:{$gte: lastDay}}},
{$match:{createdAt:{$eq:year}}},
{$project: {
month: {$month: "$createdAt"},
day:{$day:"$createdAt"},
year:{$year:"$createdAt"},
sales: "$netto",
}},
{$group:{
_id: {
"month":"$month",
"day":"$day",
"year":"$year",
},
total:{$sum: "$sales"}
}}
]);
console.log(income);
Thanks for your help