1

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

2
  • is the above aggregation not working? Commented Dec 28, 2021 at 15:04
  • No it return the empty array Commented Dec 28, 2021 at 15:06

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.