You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Mongoose中调用.substr()方法时出现的TypeError报错

修复Mongoose中使用.substr()时的TypeError问题

嘿,这个问题其实挺常见的,我来帮你拆解一下:

你遇到的TypeError: nim.substr is not a function报错,核心原因很明确——你在数字类型的值上调用了字符串专属的方法。看你提供的请求体:

{ nama: 'Ambikapathi', email: 'ambi@me.id', nim: 14520244010, password: '14520244010', repassword: '14520244010' }

这里的nim是一个纯数字(14520244010),而.substr()是JavaScript字符串的方法,数字类型根本没有这个方法,自然会抛出错误。

给你几个实用的修复方案:

方案1:临时转换为字符串再调用方法

最简单的方式,就是在使用.substr()前,用.toString()把数字转成字符串:

nim = req.body.nim;
var prodi = nim.toString().substr(3,5);

方案2:获取值时直接转为字符串

也可以在获取nim的时候就用String()函数完成转换,后续操作更省心:

const nim = String(req.body.nim);
const prodi = nim.substr(3,5);

方案3:从Schema层面优化(推荐)

如果你的业务里nim是类似学号的标识字符串,不需要参与数值计算,建议直接在Mongoose Schema里把nim字段定义为String类型:

const userSchema = new mongoose.Schema({
  nama: String,
  email: String,
  nim: String, // 定义为字符串类型
  password: String,
  repassword: String
});

这样不管前端传的是数字还是字符串,Mongoose都会自动处理成字符串类型,你以后就不用再手动转换啦。

另外小提醒:.substr(startIndex, length)的第二个参数是截取的长度,你写的substr(3,5)是从索引3(也就是第4个字符)开始,截取5个字符,确认这符合你的业务需求哦~

内容的提问来源于stack exchange,提问作者Fatih

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:27:02