Search code examples
mongooseschemanestjsmongoose-schema

NestJS - How to create nested schema with decorators


Let's say I want to build the below schema with mongoose:

const userSchema = new Schema({
  name: {
    firstName: String,
    lastName: String
  }
})

How can I do it with NestJS decorators (@Schema() & @Prop())?

I try this method, but no luck:

@Schema()
class Name {
  @Prop()
  firstName: string;

  @Prop()
  lastName: string;
}

@Schema()
class User extends Document {
  @Prop({ type: Name })
  name: Name;
}

I also don't want to use the raw() method.


Solution

  • Here's my method which works great and doesn't involve removing @schema():

    // Nested Schema
    @Schema()
    export class BodyApi extends Document {
      @Prop({ required: true })
      type: string;
    
      @Prop()
      content: string;
    }
    export const BodySchema = SchemaFactory.createForClass(BodyApi);
    
    // Parent Schema
    @Schema()
    export class ChaptersApi extends Document {
      // Array example
      @Prop({ type: [BodySchema], default: [] })
      body: BodyContentInterface[];
    
      // Single example
      @Prop({ type: BodySchema })
      body: BodyContentInterface;
    }
    export const ChaptersSchema = SchemaFactory.createForClass(ChaptersApi);
    

    This saves correctly and shows the timestamps when you have that option set on your schema