猫鼬如何计算数组嵌入式模型中的项目数

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

使用 Mongoose 架构想要计算购物车数组中的项目数如何编写函数?我想在哪里找到特定的客户并计算购物车数组的长度

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

您传递的客户 ID 是一个字符串,但它是您架构中的对象 ID,因此没有匹配的文档

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);
}

将其转换为对象 ID 应该可行