javascript - 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)
}
解决方案
使用aggregate
和$size
输入$project
是您所需要的。
测试数据 :
{
"id": "1",
"items": [1,2]
}
总计的 :
cart.aggregate([
{
$project: {sizeOfItems:{$size:"$items"} }
}
])
结果 :
{
"_id" : "1",
"sizeOfItems" : 2
}
推荐阅读
- docker - Ping 不会安装在 Docker 容器中
- django - DjangoRestFramework,我想要名称而不是 ID,
- c++ - 具有模板参数和 crtp 的类,仅按类名调用构造函数
- javascript - 像 SQL 一样使用 IndexedDB。使用不在范围内的多个索引值进行查询
- javascript - 通过在 URL 末尾附加一个变量来设置加载时的默认主题
- r - R: 为什么使用 download.file() 下载的 PNG 文件无法打开?
- java - 断字问题:没有得到负例的预期 O/P
- c++ - For 循环只比较数组的第一部分而不是整个
- sql-server - 将不常见的 Datetime 字符串转换为 Datetime 类型
- python - 如何将 python 列表发送到瓶子服务器?