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

NestJS + Mongoose 保存数据报错:字符串无法转为ObjectId

解决Mongoose中cast to objectid failed for value type string错误

问题原因

你的Post文档Schema里,categoryName字段被定义为MongooseSchema.Types.ObjectId类型,用来关联Category集合的文档,但你传入的请求数据里,categoryName是普通字符串"test"——Mongoose要求ObjectId类型的字段必须传入合法的24位十六进制MongoDB文档ID,普通字符串无法被转换为ObjectId,因此抛出这个错误。

解决方案

  • 传入合法的Category文档ID
    如果你需要关联已存在的Category文档,把请求里的categoryName替换为对应Category文档的_id值(格式是24位十六进制字符串,比如60d21b4667d0d8992e610c85):

    title: "Test"
    categoryName: "60d21b4667d0d8992e610c85" // 替换为实际Category的_id
    
  • 修改Schema字段类型
    如果你只是想存储分类名称的字符串,不需要关联Category集合,直接把categoryName的类型改为字符串即可:

    @Schema({ timestamps: true })
    class PostDocument extends Document {
        @Prop()
        title: string;
    
        @Prop()
        categoryName: string;
    }
    
  • 拆分字段(灵活处理场景)
    如果既需要关联Category文档,又要存储分类名称,可以拆分出两个字段:

    @Schema({ timestamps: true })
    class PostDocument extends Document {
        @Prop()
        title: string;
    
        @Prop({ type: MongooseSchema.Types.ObjectId, ref: 'Category' })
        categoryId: Category;
    
        @Prop()
        categoryName: string;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:23:09