【问题标题】:mongoose how to count the number of item in array embedded model猫鼬如何计算数组嵌入式模型中的项目数
【发布时间】:2021-12-28 06:07:18
【问题描述】:

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

【问题讨论】:

  • 上述聚合不起作用吗?
  • 不返回空数组

标签: node.js mongodb express backend mongoose-schema


【解决方案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 应该可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 2017-12-23
    • 2019-08-07
    • 2017-05-07
    • 2014-02-13
    • 2019-06-09
    • 2018-09-11
    相关资源
    最近更新 更多