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

618
Views
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 answers
Answer question

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 Report
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!