这是我的路由器:
reportRoutes.route('/:id').get(async (req, res) => {
try{
let id = req.params.id
console.log(req.query)
let team = req.query.team
let league_acronym = req.query.league
console.log('team',team)
let regex = new RegExp( id, 'i')
const report = await Report.find({ title: regex })
.populate({path: 'like'})
.populate({
path: 'player',
populate: [{ path: 'team' },
{
path: 'team',
populate: {
path: 'league'
}
}
]
})
if(league_acronym) {
newReport = report.filter((v,i) => {
return v.player.team.league.acronym === league_acronym && v.player.team.team_name === team
})
res.json(newReport)
} else{
res.json(report)
}
} catch (e) {
res.status(500).send()
}
})
我正在尝试设置一个通过报告并返回newReport的过滤器。
它将根据查询字符串参数进行过滤。
因为查询字符串参数将不会始终存在,所以我需要一种仅在条件存在时才对条件进行过滤的方法。有想法吗?
答案 0 :(得分:0)
只有在league_acronym
和team
中有一个值,您才能检查相应的条件
newReport = report.filter(v =>
(!league_acronym || v.player.team.league.acronym === league_acronym)
&& (!team || v.player.team.team_name === team)
)