Error while saving data in nestjs mongoose

177 Views Asked by At

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"
1

There are 1 best solutions below

1
Bogdan Onischenko On

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 }