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

如何用Node.js从REST API获取MongoDB中指定ID的比赛JSON数据

Fixing Your MongoDB Match ID Query in Express

Let's walk through the issues in your code and fix them to get the specific match data you need:

Key Issues in Your Current Code

  • Incorrect Parameter Access: Your route uses :match_id, but you're trying to fetch req.params.id—this means you're actually getting undefined for the ID, so MongoDB runs an empty query ({}) which returns all documents.
  • Mismatched Query Field: Your schema uses id as the match ID field (seen in your sample JSON: "id": 1), but your query uses {match} (shorthand for { match: match }), so it's looking for a non-existent field named match.
  • Wrong Query Method: find() returns an array of all matching documents. For a single match by ID, you should use findOne() instead.
  • Incorrect Response Value: You're returning the match variable (the parameter) instead of the actual query result eachOne.

Corrected Code

app.get('/api/matches/:match_id', (req, res) => {
  // Convert the string parameter to a number (since your schema's id is numeric)
  const matchId = parseInt(req.params.match_id);

  // Query for the single match where the "id" field matches matchId
  matches.findOne({ id: matchId })
    .then(matchData => {
      if (!matchData) {
        // Return 404 if no match is found
        return res.status(404).json({ message: 'Match not found' });
      }
      // Send the found match data as JSON
      res.json(matchData);
    })
    .catch(error => {
      // Handle database errors with a 500 status
      res.status(500).json({ error: error.message });
    });
});

Additional Notes

  • Type Conversion: req.params values are always strings, so we use parseInt to match the numeric id field in your MongoDB documents—this ensures the query matches correctly (MongoDB enforces strict type matching).
  • Error Handling: Added checks for missing matches and database errors to make your API more robust and informative for clients.
  • Query Efficiency: findOne() is more efficient than find() for single-document queries since it stops searching after finding the first match.

内容的提问来源于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:39:29