点击按钮按特定方式更新MongoDB多集合?含404错误排查
解决方案:修复404错误并实现赛事实时统计功能
一、修复/api/updateEventList 404错误
404错误的核心原因是后端未定义对应接口路由。以下是基于Node.js+Express+Mongoose的完整路由实现:
1. 定义路由文件(例如 routes/match.js)
const express = require('express'); const router = express.Router(); const MatchHistory = require('../models/MatchHistory'); const UserDB = require('../models/UserDB'); // 赛事事件与比分更新接口 router.post('/api/updateEventList', async (req, res) => { try { const { matchId, eventLine } = req.body; const isOurGoal = eventLine.includes('Goal'); // 更新赛事事件列表与比分 const updatedMatch = await MatchHistory.findOneAndUpdate( { _id: matchId }, { $push: { eventList: eventLine }, ...(isOurGoal ? { $inc: { ourScore: 1 } } : { $inc: { theirScore: 1 } }) }, { new: true } ); if (!updatedMatch) return res.status(404).json({ message: '赛事记录不存在' }); res.status(200).json({ message: '更新成功', match: updatedMatch }); } catch (err) { res.status(500).json({ message: err.message }); } }); // 球员统计更新接口 router.post('/api/updatePlayerStats', async (req, res) => { try { const { userId, statType, increment } = req.body; // 累加球员对应统计字段 const updatedPlayer = await UserDB.findOneAndUpdate( { _id: userId }, { $inc: { [statType]: increment } }, { new: true } ); if (!updatedPlayer) return res.status(404).json({ message: '球员记录不存在' }); res.status(200).json({ message: '更新成功', player: updatedPlayer }); } catch (err) { res.status(500).json({ message: err.message }); } }); module.exports = router;
2. 挂载路由到主应用(app.js)
const matchRoutes = require('./routes/match'); app.use(matchRoutes);
二、前端live-tracking.ejs实现逻辑
1. 球员统计计数器累加处理
<!-- 示例:单个球员统计模块 --> <div class="player-item" data-user-id="<%= player._id %>"> <p>球员:<%= player.name %></p> <p>进球数:<span class="stat-value"><%= player.goals %></span></p> <button onclick="updateStat('<%= player._id %>', 'goals', 1)">+1</button> </div> <script> async function updateStat(userId, statType, increment) { try { const res = await fetch('/api/updatePlayerStats', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, statType, increment }) }); const data = await res.json(); if (res.ok) { // 同步更新页面显示 const statElement = document.querySelector(`[data-user-id="${userId}"] .stat-value`); statElement.textContent = data.player[statType]; } else { alert(data.message); } } catch (err) { console.error('统计更新失败:', err); alert('更新球员统计时出错'); } } </script>
2. Next Point按钮事件处理
<!-- 示例:赛事操作区 --> <div class="match-controls"> <button onclick="submitEvent()">Next Point</button> <p>比分:<span id="our-score"><%= match.ourScore %></span> : <span id="their-score"><%= match.theirScore %></span></p> </div> <script> // 假设已通过EJS传入当前赛事ID,eventLine为组装好的事件数组 const currentMatchId = '<%= match._id %>'; let eventLine = ['Goal', '<%= currentPlayer %>', new Date().toLocaleTimeString()]; // 示例事件结构 async function submitEvent() { try { const res = await fetch('/api/updateEventList', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ matchId: currentMatchId, eventLine }) }); const data = await res.json(); if (res.ok) { // 更新页面比分 document.getElementById('our-score').textContent = data.match.ourScore; document.getElementById('their-score').textContent = data.match.theirScore; // 重置事件数组 eventLine = []; } else { alert(data.message); } } catch (err) { console.error('事件提交失败:', err); alert('提交赛事事件时出错'); } } </script>
三、MongoDB模型补充定义
确保模型与集合对应:
MatchHistory模型(models/MatchHistory.js)
const mongoose = require('mongoose'); const schema = new mongoose.Schema({ ourScore: { type: Number, default: 0 }, theirScore: { type: Number, default: 0 }, eventList: { type: Array, default: [] }, // 其他赛事相关字段 }); module.exports = mongoose.model('MatchHistory', schema, 'test.matchhistories');
UserDB模型(models/UserDB.js)
const mongoose = require('mongoose'); const schema = new mongoose.Schema({ name: String, goals: { type: Number, default: 0 }, cGoals: { type: Number, default: 0 }, // 其他球员统计字段 }); module.exports = mongoose.model('UserDB', schema, 'test.userdbs');
关键注意事项
- 确保前端请求路径与后端路由完全一致,避免拼写错误
- 所有POST请求必须设置
Content-Type: application/json - 数据库操作使用
async/await处理异步逻辑,避免回调地狱 - 更新后返回最新文档,保证页面数据与数据库同步
内容的提问来源于stack exchange,提问作者Yoshixed
相关产品推荐
相关产品推荐

