0

I am just started learning MEAN stack and I am stuck. I need to send the below query data to frontend.

router.get('/average', (req, res) => {
  Employees.aggregate([
    { $match: { "position": "sen" } },
    {
      $group: {
        _id: null,
        average: {
          $avg: "$salary"
        }
      }
    }
  ]);
});

I have tried doing this but it didn't work

router.get('/average', (req, res) => {
  Employees.find(function (err, docs) {
    res.json(docs);
  }).aggregate([
    { $match: { "position": "sen" } },
    {
      $group: {
        _id: null,
        average: {
          $avg: "$salary"
        }
      }
    }
  ]);
});
2
  • what lib are you using for mongodb? is it mongoose? Commented Dec 15, 2019 at 8:01
  • yes I am using mongoose Commented Dec 15, 2019 at 8:05

1 Answer 1

1

In the first example you are not send the data to response, and in the second case the syntax is slightly messed up.

So mongoose returns a Promise and/or aggregate value as response, so below code should work just fine:

router.get('/average', (req, res) => {
  Employees.aggregate([
    { $match: { position: 'sen' } },
    {
      $group: {
        _id: null,
        average: {
          $avg: '$salary'
        }
      }
    }
  ])
  .then((result)=>{
    res.json(result)
  })
});

Also check out the documentation for mongoose: https://mongoosejs.com/docs/api/model.html#model_Model.aggregate

Sign up to request clarification or add additional context in comments.

Comments