@Prop and mongoose options is ignored in NestJS Nested Schema

Viewed 855

I'm trying to build a Schema with a nested object in it. I want to set default values and required in the nested object but the options will get ignored.

task.entity.ts

@Schema()
export class Task {
    @Prop({ required: true }) // Is working
    language: Language

    @Prop({ type: TaskContent, required: true })
    content: TaskContent
}

class TaskContent extends Document {
    @Prop({ required: true, default: "Hello World" }) // This prop is ignored.
    message: string
}

export type TaskDocument = Task & Document
export const TaskSchema = SchemaFactory.createForClass(Task)

In my task.service.ts:

const task = new this.taskSchema({
...dataFromPostRequest
})
const result = await task.save()
return result

How can I insert an object and use the @Prop from the nested object? I don't want to set it in one class. I would like to split the content.

1 Answers

You need to build a Schema and use this as the type:

@Schema()
export class Task {
    @Prop({ required: true })
    language: Language
 
    @Prop({ type: TaskContentSchema, required: true }) // Here
    content: TaskContent
}
 
class TaskContent extends Document {
    @Prop({ required: true, default: "Hello World" })
    message: string
}
 
const TaskContentSchema = SchemaFactory.createForClass(TaskContent) // Here
 
export type TaskDocument = Task & Document
export const TaskSchema = SchemaFactory.createForClass(Task)
 
Related