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"
 }
 }
 }
 ]);
});
SuleymanSah
18k6 gold badges38 silver badges60 bronze badges
asked Dec 15, 2019 at 7:59
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

answered Dec 15, 2019 at 8:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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