javascript - 添加与用户 ID 匹配的文档总数
问题描述
我正在尝试使总订单与单个用户匹配。
这是我的订单架构:
const OrderSchema = new Schema({
lineItems: [{
product: {
type: Schema.Types.ObjectId,
ref: "Product"
},
quantity: {
type: Number
}
}],
created_at: {
type: Date,
default: Date.now
},
user: [{
type: Schema.Types.ObjectId,
ref: "User",
required: true
}]
});
这是我的猫鼬查询:
getOrderTotal: function (req, res) {
const userID = req.params.userid;
Order
.aggregate([
{ $match: { 'user': mongoose.Types.ObjectId(userID) } },
{
$lookup: {
from: "products",
localField: "lineItems.product",
foreignField: "_id",
as: "product"
}
},
{
$unwind: "$product",
},
{
$unwind: "$lineItems"
},
{
$group: {
_id: mongoose.Types.ObjectId(userID),
count: { $sum: 1 }
}
}
])
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
}
我测试的每个用户,count 字段总是返回一个 72 的值。db 中甚至没有总共 72 个订单。当我将 1 值更改为不同的数字时,它返回 72 的某个倍数,即 2 返回 144,0.5 返回 36。
解决方案
推荐阅读
- excel - 在 VBA 中为 PDF 设置的复选框未保持选中状态
- regex - 正则表达式意外行为记事本++
- python - standard_init_linux.go:211:exec 用户进程导致“没有这样的文件或目录”?
- python - 合并来自两个不同文件夹的两个图像(python)
- javascript - 用javascript生成模态
- anaconda - OSError: 找不到 lib geos_c.dll 或加载它的任何变体 ['..\Library\\lib\\geos_c.dll']
- go - 如何将内部包与 go 模块一起使用?
- python - 有没有办法验证作为参数传递的 lambda 函数只分配 True 或 False?
- java - 如何在java上处理非常大的数字?
- python - 实现极小极大算法时的递归问题