Nested data collection via function in mongoose

I don't know if its a dumb way to do this but I have a problem with this get route. I want to get all the data from mongo in the lower part (find). In that part I want to sum all data in the database.

for context: I want to display all datasets on the website and all the data as a sum.

Any idea why this isn't working?

router.get('/', function(req, res, next) {

    function getSumme(){
        stopp.aggregate([
            {$group: { 
                _id: null,
                totalLiter: {$sum: "$liter"}
            }}
        ]);
        console.log(summe);     
    };
 
    stopp.find((err, data) => {
        if (!err) {
            res.render(path + '/index', {
                data: data,
                test: 123, 
                stopps: getSumme()
            });
        } else {
            console.log('Failed to retrieve the Course List: ' + err);
      }
  });
})

Solution 1:

Few corrections in your query,

  • missed async/await method for aggregate query
  • result the sum by checking turnery operator condition
router.get('/', async function(req, res, next) {

  let result = await stopp.aggregate([
    {
      $group: { 
        _id: null,
        totalLiter: {$sum: "$liter"}
      }
    }
  ]);

  res.render(path + '/index', {
    // data: data,
    // test: 123, 
    stopps: result.length ? result[0].totalLiter : 0
  });

})