Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda