Search code examples
node.jsmongodbexpressbackendmongoose-schema

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,
        }
    }]
})


Solution

  • 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