I have 2 Mongoose collections: ExpenseCategory and Expense
var ExpenseCategorySchema = new Schema({
name: String,
totalSpentInThisMonth: Number
});
mongoose.model('ExpenseCategory', ExpenseCategorySchema);
var ExpenseSchema = new Schema({
expenseCategoryId: {type: Schema.Types.ObjectId, ref: 'ExpenseCategory'},
amount: Number,
date: Date
});
mongoose.model('Expense', ExpenseSchema);
There is a GET api
call written in Node.js to return all ExpenseCategory items
.
appRouter.route('/expensecatgories')
.get(function(req, res){
ExpenseCategory.find({}, function (expenseCategories) {
res.json(expenseCategories);
});
});
In the above GET method
I want to populate field totalSpentInThisMonth
in each expenseCategories
item before returning. This field needs to be calculated as a sum of all expense.amount
where expense.expenseCategoryId
matched the expenseCategory.id
and expense.date
is in current month.
How can I populate the field totalSpentInThisMonth
before returning expenseCategories
?