使用猫鼬查询计算交易项目总计和交易项目
在猫鼬中,我有一个交易集合。每个交易都有一个类似这样的项目列表:
var transactionItemSchema = new mongoose.Schema({
productId: String,
quantity: Number,
price: Number
});
var transactionSchema = new mongoose.Schema({
details: String,
items: [transactionItemSchema ],
}, {
timestamps: true
});
我需要通过乘以价格*数量并四舍五入到小数点后两位来计算每个项目的总价值,但是我还需要通过将一次交易中所有项目的总和相加来得出交易总金额。例如,如果我在mongo中有此交易:
[{
details: 'First Transaction',
items: [{
price: 5.2,
quantity: 2
}, {
price: 4,
quantity: 3
}]
}, {
details: 'First Transaction',
items: [{
price: 0.333,
quantity: 3
}]
}]
在进行交易时返回这样的内容:
[{
total: 22.40,
details: 'First Transaction',
items: [{
price: 5.2,
quantity: 2,
total: 10.40
}, {
price: 4,
quantity: 3,
total: 12.00
}]
}, {
total: 1.00,
details: 'Second Transaction',
items: [{
price: 0.333,
quantity: 3,
total: 1.00
}]
}]
我们有没有办法通过猫鼬的聚合来实现这一目标?
回答如下:您想要在这里$map
和$map
。
假设模型是调用$multiply
:
$multiply
或不带Transaction
:
Transaction.aggregate([
{ "$addFields": {
"items": {
"$map": {
"input": "$items",
"in": {
"$mergeObjects": [
"$$this",
{ "total": { "$round": [{ "$multiply": [ "$$this.price", "$$this.quantity" ] }, 2] } }
]
}
}
}
}}
])
$mergeObjects
运算符本质上用于数组转换,其中您提供了一个$mergeObjects
数组和一个表达式,该表达式适用于定义每个元素的对象输出的每个数组元素。此处Transaction.aggregate([
{ "$addFields": {
"items": {
"$map": {
"input": "$items",
"in": {
"price": "$$this.price",
"quantity": "$$this.quantity",
"total": { "$round": [{ "$multiply": [ "$$this.price", "$$this.quantity" ] }, 2] }
}
}
}
}}
])
与两个参数一起应用于结果“相乘”。
$map
是可选用作获取每个元素($map
和input
)的现有对象属性并将其包含在输出对象中的一种方式。另一种方法是在每个对象的输出对象中手动指定属性,如图所示。
所有这些都说,简单地处理结果post从服务器返回的内容并没有错:
$multiply
在这里简单地注意$multiply
的使用,它返回普通的JavaScript对象而不是Mongoose文档,因此允许您操纵返回结果的结构。
这是这两种方法的完整清单:
$mergeObjects
和输出:
$mergeObjects