TypeScript报错:Property 'overallTotalMarks'不存在于查询结果类型求助
问题原因
你遇到的错误是因为find()方法返回的是匹配文档的数组(类型为ExamHistoryDocument[]),而数组本身并没有overallTotalMarks属性,必须访问数组中的单个文档实例才能获取该属性。
解决方案
有两种常见的修正方式:
方式1:使用findOne()代替find()(推荐)
如果你的userId是唯一标识(一个用户对应一条考试记录),用findOne()更合适,它直接返回单个匹配文档或null,无需处理数组:
const preExam = await this.examHistoryModel.findOne({userId: examHistoryData.userId}); console.log(preExam); if (!preExam) { const newHistory = new this.examHistoryModel(examHistoryData); const result = await newHistory.save(); return result; } else { console.log(preExam.overallTotalMarks); return "You have attempted the test already!"; }
方式2:访问数组的第一个元素
如果必须使用find(),需要明确获取数组中的第一个元素(注意用可选链处理可能的空值):
const preExams = await this.examHistoryModel.find({userId: examHistoryData.userId}); console.log(preExams); if (preExams.length <= 0) { const newHistory = new this.examHistoryModel(examHistoryData); const result = await newHistory.save(); return result; } else { console.log(preExams[0]?.overallTotalMarks); return "You have attempted the test already!"; }
额外提示
- TypeScript的类型检查会严格校验变量类型,
find()返回数组类型,直接访问数组的属性会触发类型错误,这是TypeScript帮你规避潜在bug的机制。 - 从业务逻辑来看,
userId通常是唯一标识,使用findOne()更贴合场景,代码也更简洁。
内容的提问来源于stack exchange,提问作者CodeBug
相关产品推荐
相关产品推荐

