Mongoose如何对集合所有条目执行函数计算用户预测得分
Mongoose批量计算用户预测得分实现方案
首先你需要先将两个Schema注册为Mongoose模型,再按照「拉取官方结果→遍历用户预测→计算得分→批量更新」的逻辑实现即可,完整可运行代码如下:
1. 注册模型
const Result = mongoose.model('Result', resultSchema) const Predict = mongoose.model('Predict', predictSchema)
2. 自定义得分计算函数
你可以根据自己的业务规则修改下面的得分逻辑,示例默认按「单场预测完全匹配得2分」计算:
function calculateScore(correctResult, userPredict) { let totalScore = 0 // 假设官方结果数组和用户预测数组的顺序一一对应同一场比赛 for (let i = 0; i < correctResult.length; i++) { // 可自行修改规则,比如猜中胜负得1分、猜中比分再加1分 if (JSON.stringify(correctResult[i]) === JSON.stringify(userPredict[i])) { totalScore += 2 } } return totalScore }
3. 核心批量更新函数
采用bulkWrite批量更新性能远高于逐条调用save(),适合大多数场景:
async function updateMatchdayScore(targetMatchday) { try { // 拉取对应比赛日的官方正确结果 const officialResult = await Result.findOne({ matchday: targetMatchday }) if (!officialResult) { console.log(`未查询到比赛日${targetMatchday}的官方结果`) return } const correctArr = officialResult.result // 拉取该比赛日所有用户的预测记录 const userPredictList = await Predict.find({ matchday: targetMatchday }) // 生成批量更新操作列表 const updateOps = userPredictList.map(predictItem => { const finalScore = calculateScore(correctArr, predictItem.teamData) return { updateOne: { filter: { _id: predictItem._id }, update: { $set: { score: finalScore, lastUpdated: Date.now() } } } } }) // 执行批量更新 await Predict.bulkWrite(updateOps) console.log(`比赛日${targetMatchday}得分更新完成,共更新${userPredictList.length}条记录`) } catch (error) { console.error('更新得分失败:', error) } } // 调用示例:更新第3比赛日的所有用户得分 updateMatchdayScore(3)
4. 大数据量优化方案
如果预测集合数据量超过1万条,推荐用游标遍历避免一次性加载全量数据占用过高内存:
async function updateScoreWithCursor(targetMatchday) { const officialResult = await Result.findOne({ matchday: targetMatchday }) if (!officialResult) return const correctArr = officialResult.result // 用游标逐条遍历数据 const cursor = Predict.find({ matchday: targetMatchday }).cursor() for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) { const finalScore = calculateScore(correctArr, doc.teamData) await Predict.updateOne({ _id: doc._id }, { $set: { score: finalScore, lastUpdated: Date.now() } }) } console.log('所有用户得分更新完成') }
内容的提问来源于stack exchange,提问作者ManishSalian
相关产品推荐
相关产品推荐

