I have a model of Review
which has the field product
and rating
I would like to find the sum of all ratings of a specified product and find the average by dividing by 5.
JavaScript
x
16
16
1
const mongoose = require('mongoose');
2
3
const ReviewSchema = mongoose.Schema({
4
product: {
5
type: mongoose.Schema.Types.ObjectId,
6
ref: 'Product',
7
required: true,
8
},
9
rating: {
10
type: Number,
11
required: true,
12
},
13
});
14
15
module.exports = mongoose.model('Review', ReviewSchema);
16
how would I aggregate through all ratings and filter by product to find the sum?
Advertisement
Answer
I’m assuming your using nodejs , here is how I would go about doing this
JavaScript
1
20
20
1
const ReviewsModel = require('../Models/Review')
2
router.get('/average',async (req,res)=>{
3
try {
4
const reviewsPromise = await ReviewsModel.find({}).populate('product')
5
if(reviewsPromise[0] == undefined) throw new Error('no reviews')
6
7
const reviewsOfSpecifiedProduct= reviewsPromise.filter(rev=> rev.product.id == specifiedProductId)
8
const sumOfRatings = reviewsOfSpecifiedProduct
9
.map(rev=>rev.rating)//map to list of only ratings
10
.reduce((a, b)=> a + b , 0)
11
const ratingsAverage = sumOfRatings / 5
12
13
14
res.json(ratingsAverage)
15
} catch (error) {
16
console.log(error)
17
//handle the errors here
18
}
19
})
20