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.
const mongoose = require('mongoose'); const ReviewSchema = mongoose.Schema({ product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true, }, rating: { type: Number, required: true, }, }); module.exports = mongoose.model('Review', ReviewSchema);
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
const ReviewsModel = require('../Models/Review') router.get('/average',async (req,res)=>{ try { const reviewsPromise = await ReviewsModel.find({}).populate('product') if(reviewsPromise[0] == undefined) throw new Error('no reviews') const reviewsOfSpecifiedProduct= reviewsPromise.filter(rev=> rev.product.id == specifiedProductId) const sumOfRatings = reviewsOfSpecifiedProduct .map(rev=>rev.rating)//map to list of only ratings .reduce((a, b)=> a + b , 0) const ratingsAverage = sumOfRatings / 5 res.json(ratingsAverage) } catch (error) { console.log(error) //handle the errors here } })