Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Problem with getting average rating from mongodb in node.js express

I have a node.js express back-end with a mongodb database on the cloud(mongodb atlas). This is the Post object and I want to get the average grade from reviewerComments and userComments.

import mongoose from 'mongoose'

const postSchema = mongoose.Schema({
    game: {
    },
    reviewerComments: [
        {
            author: String,
            authorEmail: String,
            avatar: String,
            title: String,
            text: String,
            grade: Number,
            date: String
        }
    ],
    userComments: [
        {
            author: String,
            authorEmail: String,
            text: String,
            grade: Number,
            date: String
        }
    ]
}, {
    timestamps: true
})

const Post = mongoose.model('Post', postSchema)

export default Post

I have a API route that calls this function

export const getAverageGrades = async (req, res) => {
    const { id } = req.query
    try {
        const post = await Post.aggregate([
            {
                $match:
                    {
                        _id: mongoose.Types.ObjectId(`${id}`)
                    }
            },
            {
                $unwind: "$reviewerComments"
            },
            {
                $group:{
                    _id:{
                        "comment_id": "$reviewerComments.id",
                        "title": "$reviewerComments.title",
                        "grade": "$reviewerComments.grade",
                    },
                    avg_rating: {$avg:"reviewerComments.grade"}
                }
            },
            {
                $project:{
                    "id": "$_id.rating_id",
                    "title": "$_id.title",
                    "avg_rating": "$avg_rating"  // avg_rating returns null
                }
            }
        ])
        res.status(200).json(post);
    } catch (error) {
        console.log(error.message)
        res.status(404).json({ message: error.message });
    }
}

This function is returning a response where avg_rating is null, what am I doing wrong?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!