如何用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 fetchreq.params.id—this means you're actually gettingundefinedfor the ID, so MongoDB runs an empty query ({}) which returns all documents. - Mismatched Query Field: Your schema uses
idas 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 namedmatch. - Wrong Query Method:
find()returns an array of all matching documents. For a single match by ID, you should usefindOne()instead. - Incorrect Response Value: You're returning the
matchvariable (the parameter) instead of the actual query resulteachOne.
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.paramsvalues are always strings, so we useparseIntto match the numericidfield 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 thanfind()for single-document queries since it stops searching after finding the first match.
内容的提问来源于stack exchange,提问作者stone rock
相关产品推荐
相关产品推荐

