0

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

1
  • .toArray() is a node native driver of mongodb function & It seems you are using Mongoose. don't use that. Commented Sep 1, 2019 at 11:36

1 Answer 1

1

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);
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Tried this & still it doesn't return anything
Can you log values returned from aggregation query before if block starts, e.g. console.log(error, data) and also before aggregation query starts to ensure if route get /generate-report is called
Got it working, I was missing the req, and next in my route function but also turns out i misplaced a parenthesis after the array, which was stopping the res being called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.