我在Node js中学习,我有一个节点swagger api。我正在尝试根据2个输入团队检索游戏统计数据。我用这个函数查询mongodb:
function getTeamVsTeamRecord(req, res) {
var team1 = req.swagger.params.team1.value;
var team2 = req.swagger.params.team2.value;
stats.find({
game: /2016/,
$or:[
{'data.home.abbr': team1, 'data.away.abbr': team2},
{'data.away.abbr': team1, 'data.home.abbr': team2}
]}).toArray(function(err, results){
if (err) {
console.error(err);
res.status(500).json({error: 'error.code', message: 'An error happened in the server !'})
}
if (typeof results !== 'undefined' && results.length > 0) {
console.log("search returned: " + results.length + " results");
console.log(results);
res.json(results);
}
else {
res.status(500).json({error: 'error 1', message: 'search returned nothing'})
}
});
}
结果对象的输出如下所示:
[ { _id: 59ea18c21fff646c417b078c,
game: '2016100201',
data:
{ home: [Object],
away: [Object],
drives: [Object],
scrsummary: [Object],
weather: null,
media: null,
yl: '',
qtr: 'Final',
note: null,
down: 0,
togo: 0,
redzone: true,
clock: '00:34',
posteam: 'ATL',
stadium: null },
nextupdate: 246 },
{ _id: 59ea18c61fff646c417b0bac,
game: '2016122401',
data:
{ home: [Object],
away: [Object],
drives: [Object],
scrsummary: [Object],
weather: null,
media: null,
yl: '',
qtr: 'Final',
note: null,
down: 0,
togo: 0,
redzone: true,
clock: '00:44',
posteam: 'CAR',
stadium: null },
nextupdate: 318 } ]
正如您所看到的,我在此查询中检索了2组游戏统计信息。我的问题是它失败了模式验证,因为swagger期望json语法。我尝试了JSON.stringify,这导致错误的数组错误。我可以成功发送
res.json = results[0].data
作为响应,但仅当数组中有1个项目时才有效。有没有办法将整个数组作为json响应发送?
答案 0 :(得分:0)
我最终创建了一个对象" o"并将数组中的结果添加到此对象,如下所示:
function getTeamVsTeamRecord(req, res) {
var team1 = req.swagger.params.team1.value;
var team2 = req.swagger.params.team2.value;
var year = req.swagger.params.year.value;
var o = {};
stats.find({
game: {$regex: ".*" + year + ".*"},
$or:[
{'data.home.abbr': team1, 'data.away.abbr': team2},
{'data.away.abbr': team1, 'data.home.abbr': team2}
]}).toArray(function(err, results){
if (err) {
console.error(err);
res.status(500).json({error: 'error.code', message: 'An error happened in the server !'})
}
if (typeof results !== 'undefined' && results.length > 0) {
for (var i = 0; i < results.length; i++) {
var game = "res" + i;
o[game] = results[i];
}
res.json(o);
}
else {
res.status(500).json({error: 'error 1', message: 'search returned nothing'})
}
});
}