Reputation: 11
I'm trying to query a mongoDB collection so that I can return the sum of each suppliers total amount invoiced, using the mongoshell i can get the aggregate function working using
db.invoice.aggregate ([
{$group: {_id: "$supplier_name",
total: {$sum: "$invoice_amount"} } }
])
in the backend of my application i have a routes folder set up, here I can succesfully query my db with things such as
invoiceRoute.route('/supplier-count').get((req, res) => {
Invoice.count({supplier_name: 'xyx'}, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data);
}
})})
However when i try run this code I am using for the aggregate function doesn't return anything
invoiceRoute.route('/generate-report').get((res) => {
Invoice.aggregate ([
{$group:
{_id: "$supplier_name",
total: {$sum: "$invoice_amount"}} }
]), (error, data) => {
if (error) {
return next(error)
} else {
res.json(data);
}}});
I've tried using the .toArray function as suggested in other answers but it responds with
Invoice.aggregate(...).toArray is not a function
I've checked the requests using postman and it times out before receiving a response however other requests do return responses.
Any advice is appreciated
Upvotes: 0
Views: 217
Reputation: 4700
You are missing req
and next
in your route function: invoiceRoute.route('/generate-report').get((res) => {
invoiceRoute.route('/generate-report').get((req, res, next) => {
Invoice.aggregate([{
$group: {
_id: "$supplier_name",
total: {
$sum: "$invoice_amount"
}
}
}]), (error, data) => {
if (error) {
return next(error)
}
res.json(data);
}
});
Upvotes: 1