首页 > 解决方案 > MEAN-如何找到数组的长度?

问题描述

这是我的猫鼬模式

let ItemSchema = new Schema({

    productId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Product",
    },
    quantity: {
        type: Number,
        required: true,
        min: [1, 'Quantity can not be less then 1.']
    },
    price: {
        type: Number,
        required: true
    },
    total: {
        type: Number,
        required: true,
    }
}, {

})

const CartSchema = new Schema({
    userId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
    },
   items:   [ItemSchema],
  subTotal: {
        default: 0,
        type: Number
    }
}, {
})
module.exports = mongoose.model('cart', CartSchema);

找到项目数组长度的最佳方法是什么我只想要项目数组的长度

建议我一个函数来获取长度

这就是我想要做的

 exports.arrlen = function (req, res){
     var len = cart.items.length
     console.log(len)
 }

标签: javascriptnode.jsarraysmongodb

解决方案


使用aggregate$size输入$project是您所需要的。

测试数据 :

{
    "id": "1",
    "items": [1,2]
}

总计的 :

cart.aggregate([
    {  
        $project: {sizeOfItems:{$size:"$items"} }
    }
])

结果 :

{
    "_id" : "1",
    "sizeOfItems" : 2
}

推荐阅读