You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js和Mongoose获取指定赛季JSON对象?接口返回null

问题分析与解决方案

首先,我一眼就发现了几个关键问题,导致你的API请求返回null,咱们一步步来排查修复:

1. Mongoose Schema字段与实际数据不匹配

你提供的JSON响应示例里,匹配的ID字段是"id": 1,但你的matchSchema里定义的是match_id:{ type:Number, required:true }——这直接导致Mongoose查询不到数据:数据库里存的字段是id,但你用match_id去映射,相当于在找一个不存在的字段,自然返回空结果。

修复方法:把Schema里的match_id改成id,和实际数据的字段名完全对应:

const matchSchema = new Schema({
  id:{ type:Number, required:true }, // 修正为和JSON一致的字段名
  season:{ type:Number, required:true },
  city:{ type:String, required:true },
  date:{ type:Number },
  team1:{ type:String, required:true },
  team2:{ type:String, required:true },
  toss_winner:{ type:String, required:true },
  toss_decision:{ type:String, required:true },
  dl_applied:{ type:Number },
  winner:{ type:String, required:true },
  win_by_runs:{ type:Number, required:true },
  win_by_wickets:{ type:Number, required:true },
  player_of_match:{ type:String, required:true },
  venue:{ type:String, required:true },
  umpire1:{ type:String, required:true },
  umpire2:{ type:String, required:true },
  umpire3:{ type:String }
});

2. 潜在的路由冲突(需提前规避)

你注释掉的路由/api/matches/:match_id和当前的/api/matches/:season路径格式完全一致——如果之后你解开注释,Express会把所有请求优先匹配到第一个路由。比如你请求/api/matches/2008,Express会把2008当作match_id处理,而不是season,直接导致查询逻辑错误。

建议优化:修改路由路径,让两个接口明确区分:

  • 按ID查询:/api/matches/id/:match_id
  • 按赛季查询:/api/matches/season/:season

3. 验证数据类型一致性

你的查询代码里把req.params.season转成parseInt(Season)是正确的,因为Schema里season定义为Number类型。但要确保数据库里的season字段确实是数字类型,而不是字符串(比如存成"2008"而不是2008)。如果类型不匹配,数字2008和字符串"2008"无法匹配,也会返回空。

快速验证方法:直接在MongoDB客户端执行查询,确认是否有数据:

db.matches.find({ season: 2008 })

如果这个查询能返回结果,说明数据类型没问题;如果返回空,需要批量将数据库里的season字段从字符串转换成数字。

测试修复效果

修改完Schema和路由(如果调整的话),重启服务器,再访问http://localhost:5000/api/matches/2008,应该就能正常返回对应赛季的所有匹配数据了。


内容的提问来源于stack exchange,提问作者stone rock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:38:49