Discord Bot调用MongoDB时返回NaN与Undefined问题求助
问题分析与修复方案
你的代码存在几个关键问题,直接导致了undefined、NaN的输出:
核心问题点
- 动态属性访问错误:你用
trial.arrayPoint读取属性,但arrayPoint是变量,点语法只能识别字面量属性名,必须改用方括号语法trial[arrayPoint]才能正确读取动态属性。 - Update操作逻辑错误:
- 查询条件
{name: {arrayPoint}}完全不符合需求,你需要匹配的是包含arrayPoint对应属性的文档,应该写成{ [arrayPoint]: { $exists: true } } $set: {value}会错误地新增value字段,而非更新目标属性,正确写法是$set: { [arrayPoint]: value }
- 查询条件
- 异步操作未等待:
insertOne和updateOne都是异步函数,必须加await确保操作执行完成,否则会出现数据不一致问题。 - 变量未声明:
tempObj、value未用let/const声明,会变成全局变量,引发潜在bug。
修复后的完整代码
async function checkPoint(arrayPoint, collection){ const trial = await collection.findOne({ [arrayPoint]: { $exists: true }}) if(trial == null){ console.log(`Player didn't exist, ergo we make a new area for them, for our good player buddy ${arrayPoint}`) const tempObj = "1"; await collection.insertOne({ [arrayPoint]: tempObj }) } else { console.log(`It seems we have data ! Aha ! ${arrayPoint}`) const currentValue = trial[arrayPoint]; console.log(currentValue) let value = parseInt(currentValue); console.log(value) value += 1; const newValue = value.toString(); console.log(newValue) await collection.updateOne( { [arrayPoint]: { $exists: true } }, { $set: { [arrayPoint]: newValue } } ) } }
进阶优化建议
可以用MongoDB的findOneAndUpdate结合upsert: true,把查询、插入、更新逻辑合并为一步,避免竞态条件:
async function checkPoint(arrayPoint, collection){ const result = await collection.findOneAndUpdate( { [arrayPoint]: { $exists: true } }, { $inc: { [arrayPoint]: 1 } }, // 直接数值递增,无需手动类型转换 { upsert: true, returnDocument: 'after' } ) if(result.lastErrorObject.upserted){ console.log(`Created new entry for player ${arrayPoint}`) } else { console.log(`Updated player ${arrayPoint} to value: ${result.value[arrayPoint]}`) } }
注:这里建议把存储值改为数字类型,比字符串更适合计数场景。
内容的提问来源于stack exchange,提问作者Dougal McSmith
相关产品推荐
相关产品推荐

