Below is a structured format on how to define Mongoose schemas in a NestJS application. This structured format ensures clarity, organization, and adherence to best practices.

Schema Definition

Define the schema using the @Schema() decorator. The @Schema() decorator accepts an optional configuration object. The configuration object can be used to define the schema’s timestamps. Use the system schema for internal fields. For example, system.createdAt and system.modifiedAt.
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';

@Schema({
  timestamps: { createdAt: 'system.createdAt', updatedAt: 'system.modifiedAt' },
})
export class Entity {
  // ... schema properties

  @Prop({ type: SystemSchema })
  system?: System;
}

Disable automatically _id generation

MongoDB automatically generates an _id field for each document. This field is of type ObjectId. If you want to disable this behavior for example if this is not a root document, you can set the _id field to false.
@Schema({ _id: false })
export class UserGoal {
  // ... schema properties
}

Define Schema Properties

Define the schema properties using the @Prop() decorator. The decorator accepts an optional configuration object. The configuration object can be used to define the schema property’s type, default value, and other options.
@Schema({})
export class User {
  @Prop()
  firstName: string; // Required field

  @Prop({ required: false })
  firstName?: string; // Not required field

  @Prop({ type: [UserGoalSchema], required: false })
  goals?: UserGoal[]; // Reference to another schema

  @Prop({ enum: Gender })
  gender: Gender; // Enum field

  // Other fields...
}

Create Schema Factory

The EntitySchema can then be used to create a Mongoose model.
import { SchemaFactory } from '@nestjs/mongoose';

export const EntitySchema = SchemaFactory.createForClass(Entity);

Export Schema

Export the schema class itself and as Document from the mongoose package. This is useful for defining the type of a Mongoose model and working with the schema in other parts of the application.
import { Document } from 'mongoose';

export type UserDocument = User & Document;