1

I have a post schema:

@Schema({ timestamps: true })
class PostDocument extends Document {
    @Prop()
    title: string;

    @Prop({ type: MongooseSchema.Types.ObjectId, ref: 'Category' })
    categoryName: Category

}

And when I am trying to save the data, I am getting error:

cast to objectid failed for value type string

Request data:

title: "Test"
categoryName: "test"
kittu
  • 6,662
  • 21
  • 91
  • 185

1 Answers1

1

Based on the error message you've provided, it looks like you've added an ObjectId type to the categoryName field in your Mongoose schema. However, you are trying to save a string value to this field. To resolve this issue, you can either change the field type annotation to string type, or pass a valid ObjectId to the categoryName field.

@Schema({ timestamps: true })
class PostDocument extends Document {
    @Prop()
    title: string;

    @Prop()
    categoryName: string
}

// data: { title: "Test", categoryName: "test" }

OR

@Schema({ timestamps: true })
class PostDocument extends Document {
    @Prop()
    title: string;

    @Prop({ type: Types.ObjectId, ref: 'Category' })
    categoryId: Types.ObjectId

}

// data: { title: "Test", categoryId: category.id }
  • I'm not OP but offered the bounty because I have the same issue. I have essentially the same schema that he does except: ``` @ApiProperty() @Prop({type: [MongooseSchema.Types.ObjectId], ref: Role.name}) roles: Role[]; ``` And this is my role: ``` export class Role extends Document { @Prop() name: string; } ``` This structure needs to remain in tact however, when creating roles, I get an error stating cast to object id is wrong. – Quesofat Apr 06 '23 at 01:45