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
user12187201user12187201
-
what lib are you using for mongodb? is it mongoose?Aritra Chakraborty– Aritra Chakraborty2019年12月15日 08:01:24 +00:00Commented Dec 15, 2019 at 8:01
-
yes I am using mongooseuser12187201– user121872012019年12月15日 08:05:14 +00:00Commented Dec 15, 2019 at 8:05
1 Answer 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
lang-js