【问题标题】:MEAN-How to find the length of an array?MEAN-如何找到数组的长度?
【发布时间】:2021-10-26 05:32:14
【问题描述】:

这是我的猫鼬模式

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

找出 items 数组长度的最佳方法是什么 我只想要 items 数组的长度

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

这就是我想要做的事情

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

【问题讨论】:

    标签: javascript node.js arrays mongodb


    【解决方案1】:

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

    测试数据:

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

    聚合:

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

    结果:

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

    【讨论】:

    • 能否详细解释一下
    • aggregationsizeproject aggregate 处理数据记录并返回计算结果。 $size 计算并返回数组中的项目总数。 $project 将带有请求字段的文档传递到管道中的下一个阶段。
    • 不能用我尝试的方法找到长度
    • find 用于查询已有数据,需要投影一个新的字段,其值为另一个数组字段的大小。
    • 基本上我想为数组中的项目数运行一个for循环,因为我需要先找到数组的长度。你能建议我一些执行循环的方法吗?如果你让我解释,那将非常感谢。我也想在节点 js 中使用 Web API 执行它
    【解决方案2】:

    我犯了一个小错误,首先我需要得到所有,然后我才能通过 web API 找到它的长度

    这是我的 API 文件

    exports.arrlen = async function (){
        try{
       //made changes here\\
      let cart = await cartRepository.cart();
                let len = cart.items.length
                console.log(len)
         }
    catch  (err){
        console.log(err)
    
    }
    }
    

    这是我的购物车存储库文件

    exports.cart = async () => {
        const carts = await Cart.find().populate({
            path: "items.productId",
            select: " name imageName category colour size discription price total"
        });;
        return carts[0];
    };
    

    【讨论】:

    • 你想要哪一个,A:统计集合中的文档。 B:计算一个文档中的数组字段大小。
    • 我只是想在for循环中使用它
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2010-12-25
    相关资源
    最近更新 更多