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

615
Vistas
mongoose how to count the number of item in array embedded model

Working on Mongoose schema want to count the number of item in cart array how can write the function? Where I want to find particular customer & count the length of the Cart Array

async function countcartproduct(Customer_id){
    console.log(Customer_id);
    const total = await CustomerCart.aggregate([{$match:{Customer_id:Customer_id}},{$project:{Cart:{$size:'$Cart'}}}]);
    console.log(total);
}
var CustomerCart = mongoose.Schema({
    Customer_id:{
       type:mongoose.Schema.Types.ObjectId,
       ref:'Customers'
    },
    Cart:[{
        Product_id:{
             type:String,
             require:true
        },
        Product_Name:{
            type:String,
            require:true,
        },
        Product_Price:{
            type:Number,
            require:true,
        },
        Product_Quantity:{
            type:Number,
            require:true,
            default:1,
        }
    }]
})

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

the customer id that you are passing is going as a string but it is object id in your schema, so no documents were matching

async function countcartproduct(Customer_id) {
    console.log(Customer_id);
    const total = await CustomerCart.aggregate(
        [{
            $match: {
                Customer_id: mongoose.Types.ObjectId(Customer_id)
            }
        },
        {
            $project: {
                Cart: {
                    $size: '$Cart'
                }
            }
        }]);
    console.log(total);
}

converting it to object id should work

over 4 years ago · Santiago Trujillo Denunciar
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