Node.js 计算对象数组字段的和
使用Express作为web框架,Mongo作为后端,开发节点应用程序。目前,我有一个Mongoose数据模式,其中包含玩家和相关统计数据。以下是该结构的匿名示例:Node.js 计算对象数组字段的和,node.js,mongodb,express,Node.js,Mongodb,Express,使用Express作为web框架,Mongo作为后端,开发节点应用程序。目前,我有一个Mongoose数据模式,其中包含玩家和相关统计数据。以下是该结构的匿名示例: name: 'Player Name', image: 'image-location', position: 'Guard', description: 'Player Detail', __v: 6, weight: 200, dob: 1993-08-03T05:00:00.000Z, home
name: 'Player Name',
image: 'image-location',
position: 'Guard',
description: 'Player Detail',
__v: 6,
weight: 200,
dob: 1993-08-03T05:00:00.000Z,
hometown: 'town-name',
country: 'country-name',
height_feet: 6,
height_inches: 4,
season: [
{
year: '2012-2013',
grade: 'Freshman',
gp: 18,
gs: 0,
mpg: 6.9,
fg: 0.348,
tp: 0.278,
ft: 1,
rpg: 0.8,
apg: 1,
spg: 0.3,
bpg: 0,
ppg: 1.4
},
{
year: '2013-2014',
grade: 'Sophomore',
gp: 36,
gs: 7,
mpg: 20.3,
fg: 0.432,
tp: 0.4,
ft: 0.643,
rpg: 1.6,
apg: 1.1,
spg: 0.2,
bpg: 0.1,
ppg: 7.1
},
{
year: '2014-2015',
grade: 'Junior',
gp: 34,
gs: 33,
mpg: 27.5,
fg: 0.449,
tp: 0.391,
ft: 0.755,
rpg: 2.9,
apg: 2,
spg: 0.8,
bpg: 0.1,
ppg: 10.1
},
{
year: '2015-2016',
grade: 'R. Senior',
gp: 8,
gs: 8,
mpg: 31.6,
fg: 0.425,
tp: 0.291,
ft: 0.6,
rpg: 2.9,
apg: 1.9,
spg: 0.6,
bpg: 0.3,
ppg: 12
},
{
year: '2016-2017',
grade: 'Senior',
gp: 35,
gs: 35,
mpg: 33.3,
fg: 0.473,
tp: 0.384,
ft: 0.795,
rpg: 4.6,
apg: 2.7,
spg: 1.2,
bpg: 0,
ppg: 15.1
}
]
}
作为一个整体,我对Mongo和Node还是相当陌生的,所以请原谅我的基本问题。我如何计算总赛季数的特定统计数据的平均值(例如,每场比赛4年的平均分数)
这里的目标是计算值,使其可用,并在播放器页面的获取路径上传递。以下是我在播放器页面上的路线:
router.get("/:id", function(req, res){
Player.findById(req.params.id).populate("comments").exec(function(err, foundPlayer){
if(err){
console.log(err);
} else {
console.log(foundPlayer)
res.render("players/show", {player: foundPlayer});
}
});
});
如何计算该值并将其用于播放器页面?您必须迭代四季数组并找到平均值。例如:
const{seasure}=
设平均值=0;
如果(季节长度){
设总数=0
季节图({gp})=>(总计+=gp))
平均值=总/季节长度
}
变量平均值会给你答案。我已经展示了一个计算gp平均值的示例,您必须迭代seasons数组并找到平均值。例如:
const{seasure}=
设平均值=0;
如果(季节长度){
设总数=0
季节图({gp})=>(总计+=gp))
平均值=总/季节长度
}
变量平均值会给你答案。我展示了一个计算gp平均值的示例,我们可以使用聚合管道直接在查询中计算平均值
db.collection.aggregate([
{
$match: {
_id: "playerId1" // this needs to be of type ObjectId, it should be something like mongoose.Types.ObjectId(req.params.id) in your case
}
},
{
$unwind: "$season" // unwind the season array to get a stream of documents, and to be able to calculate the average of ppg
},
{
$group: { // then group them again
_id: "$_id",
averagePointsPerGame: {
$avg: "$season.ppg"
},
season: {
$push: "$season"
}
}
}
])
你可以在这里测试
希望它有帮助我们可以使用聚合管道直接在查询中计算平均值
db.collection.aggregate([
{
$match: {
_id: "playerId1" // this needs to be of type ObjectId, it should be something like mongoose.Types.ObjectId(req.params.id) in your case
}
},
{
$unwind: "$season" // unwind the season array to get a stream of documents, and to be able to calculate the average of ppg
},
{
$group: { // then group them again
_id: "$_id",
averagePointsPerGame: {
$avg: "$season.ppg"
},
season: {
$push: "$season"
}
}
}
])
你可以在这里测试
希望能有帮助