Mongoose类型转换错误:TimePeriod字段无法转字符串为数字
问题排查与解决
核心错误原因
报错Cast to Number failed for value "undefined58" (type string) at path "TimePeriod"的根源有两个:
taxedamount是字符串类型:toFixed(0)方法返回的是字符串,直接和Number类型的Schema字段(TimePeriod、TaxesPaidInTotal等)做加法时,会触发字符串拼接而非数值相加。如果字段初始值为undefined(比如新创建的文档未给TimePeriod赋值),就会得到"undefinedXX"这种非法字符串,导致Mongoose无法转换为Number类型。- 字段初始化缺失:创建新
usertaxschema文档时,未给TimePeriod赋值,导致该字段初始为undefined,后续和字符串类型的taxedamount相加时出现异常。
额外的字段不匹配问题
除核心报错外,代码里还有多处Schema字段名不匹配的问题,会导致数据无法正确更新:
- 用户税费Schema定义的是
TaxesPaidInTotal,但创建新文档时写的是TakesPaidThisPeriod(拼写错误,且Schema中无此字段) - 主税费Schema定义的字段是
TotalTaxesAllTime、TaxesCollectedThisPeriod、TaxesInBalance,但代码里用的是chubster.TotalTaxesPaid、chubster.taxesavailable,这些字段在Schema中不存在,更新不会生效。
修复步骤
1. 修正taxedamount的类型
把toFixed(0)返回的字符串转换为数字,用parseInt或Number包裹:
const taxedamount = parseInt(((percent/100)*original).toFixed(0), 10) // 或者 const taxedamount = Number(((percent/100)*original).toFixed(0))
2. 补全新文档的字段初始化
创建新usertaxschema文档时,补上TimePeriod字段的初始值(设为0),同时删除错误的拼写字段:
const newSchema = new usertaxschema({ User: User, TaxesPaidInTotal: 0, TimePeriod: 0 // 补上这个字段 })
3. 修正主税费Schema的字段名匹配
将代码中更新主税费的字段名改为Schema中定义的正确名称:
// 原错误代码 // chubster.TotalTaxesPaid += taxedamount // chubster.taxesavailable += taxedamount // 修正后 chubster.TotalTaxesAllTime += taxedamount chubster.TaxesCollectedThisPeriod += taxedamount chubster.TaxesInBalance += taxedamount // 根据业务需求选择对应字段
4. 可选:添加字段存在性检查
在更新主税费文档前,检查chubster是否存在,避免undefined报错:
const chubster = await maintaxschema.findOne({Taxes:'Main'}) if (!chubster) { const newMainTax = new maintaxschema({ Taxes: 'Main', TotalTaxesAllTime: 0, TaxesCollectedThisPeriod: 0, TaxesInBalance: 0 }) await newMainTax.save() return taxedamount }
修复后的完整函数示例
const usertaxschema = require('./schemas/usertaxschema') const maintaxschema = require('./schemas/maintaxschema') async function taxUser(User, original, percent) { const taxedamount = parseInt(((percent/100)*original).toFixed(0), 10) const data = await usertaxschema.findOne({User: User}) if (!data) { const newSchema = new usertaxschema({ User: User, TaxesPaidInTotal: 0, TimePeriod: 0 }) await newSchema.save().catch((err) => console.log(err)) return 0 } const chubster = await maintaxschema.findOne({Taxes: 'Main'}) if (!chubster) { const newMainTax = new maintaxschema({ Taxes: 'Main', TotalTaxesAllTime: 0, TaxesCollectedThisPeriod: 0, TaxesInBalance: 0 }) await newMainTax.save() return taxedamount } chubster.TotalTaxesAllTime += taxedamount chubster.TaxesCollectedThisPeriod += taxedamount chubster.TaxesInBalance += taxedamount data.TaxesPaidInTotal += taxedamount data.TimePeriod += taxedamount await chubster.save() await data.save() return taxedamount }
内容的提问来源于stack exchange,提问作者Pickle
相关产品推荐
相关产品推荐

