node.js - 如何使用 mongoose、node、在数组中查找 sum 对象
问题描述
这是我的收藏...
var emp = new Schema({
names: String,
details: [{
date: String,
wage: String,
sack: String,
sellername: String
}]
});
集合的可能输出
{ name: john
details: [{
date:12-01-2019
wage:210
sack:10
sellername: cristy
}]
details: [{
date:12-01-2019
wage:210
sack:10
sellername: cristy
}]
details: [{
date:12-01-2019
wage:210
sack:10
sellername: cristy
}]
}
我需要添加字段工资的值并将其显示在车把模板中作为总计..这里我需要的是通过过滤一些标准来总结对象数组中的工资值我尝试了很多方法这里有一些
Person.aggregate([{
"$match": {
"name": req.body.name
}
},
{
"$addFields": {
"total": {
"$sum": "$details.wage"
}
}
}
]).exec((err, data) => {
if (err) console.log(err);
console.log(data);
});
我的工作代码显示值
Person.find({
names: req.body.woker
}) // <=> wrapper for Model.find() ...
.then(documents => {
// create context Object with 'usersDocuments' key
const context = {
usersDocuments: documents.map(documents => {
return {
details: documents.details,
}
})
}
console.log(context.usersDocuments)
// rendering usersDocuments from context Object
res.render('employee/individuallist', {
employeeName: req.body.woker,
usersDocuments: context.usersDocuments,
})
})
.catch(error => res.status(500).send(error))
})
我的车把模板代码
<table class="table table-striped" id="list">
<thead>
<tr>
<th>Date</th>
<th>Work of (Seller Name)</th>
<th>Number of sacks</th>
<th>Kooli</th>
</tr>
</thead>
<tbody>
{{#each usersDocuments}}
{{#each this.details}}
<tr>
<td>{{this.date}}</td>
<td>{{this.sellername}}</td>
<td>{{this.chack}}</td>
<td>{{this.kooli}}</td>
</tr>
{{/each}}
{{/each}}
<tr>
<td colspan="3">Total Amount</td>
<td>{{this.total}}</td>
</tr>
</tbody>
</table>
解决方案
似乎因为details
是一个数组,您不能只针对每个项目wage
,"$details.wage"
您可能需要展开(参见示例用法)该数组将产生多个条目,这些条目将具有一个details
您可以使用的对象details.wage
也许更简单的解决方案是使用reduce来聚合总数:
Person.aggregate([{
"$match": {
"name": req.body.name
}
},
{
"$addFields": {
"total": {
"$reduce": {
input: "$details",
initialValue: 0,
in: {
$add: ["$$value", "$$this.wage"]
}
}
}
}
}
]).exec((err, data) => {
if (err) console.log(err);
console.log(data);
});
推荐阅读
- azureservicebus - 为什么 Azure 服务总线队列不能保证 FIFO?
- google-cloud-platform - Aoutoml 实体提取的活动批处理请求的数量,
- class - 从接口继承但在 UML 图中实现附加方法的类
- opengl - 在 GLSL 中使用 int 时渲染中断
- python - TypeError:int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”(settings.py)
- python-3.x - 标记是否在熊猫数据框的另一列中出现值?
- android - 为什么即使我在清单文件中设置了 android:configChanges="orientation|screenSize" 我的活动也会重新启动
- python - 你如何让机器人在消息中下一行?
- c# - 如何遍历项目列表并尝试添加新的补间
- python - 如何在 Kaggle (python) 上增加 RAM 大小?