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"
Based on the error message you've provided, it looks like you've added an
ObjectIdtype to thecategoryNamefield 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 thecategoryNamefield.OR