A schema defines the shape and rules for data in your app. It helps NestJS know what data looks like and how to store it.
0
0
Schema definition in NestJS
Introduction
When you want to create a model for data stored in a database.
When you need to validate data structure before saving it.
When you want to organize data fields and types clearly.
When you want to connect your app with MongoDB using Mongoose.
When you want to reuse data structure rules across your app.
Syntax
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class Item extends Document { @Prop({ required: true }) name: string; @Prop() description?: string; @Prop({ default: 0 }) quantity: number; } export const ItemSchema = SchemaFactory.createForClass(Item);
Use @Schema() to mark a class as a schema.
Use @Prop() to define each field with options like required or default.
Examples
This schema defines a User with required username and email, and an optional age.
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class User extends Document { @Prop({ required: true }) username: string; @Prop({ required: true }) email: string; @Prop() age?: number; } export const UserSchema = SchemaFactory.createForClass(User);
This schema adds automatic timestamps for created and updated times.
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema({ timestamps: true }) export class Post extends Document { @Prop({ required: true }) title: string; @Prop() content?: string; } export const PostSchema = SchemaFactory.createForClass(Post);
Sample Program
This example shows a Product schema with a required name, a stock number defaulting to 0, and an optional description.
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class Product extends Document { @Prop({ required: true }) name: string; @Prop({ default: 0 }) stock: number; @Prop() description?: string; } export const ProductSchema = SchemaFactory.createForClass(Product);
OutputSuccess
Important Notes
Schema classes extend Document to get MongoDB document features.
Use SchemaFactory.createForClass() to generate the schema from the class.
You can add options like timestamps to track creation and update times automatically.
Summary
Schema definition sets the shape and rules for data in NestJS apps.
Use @Schema() and @Prop() decorators to build schemas.
Schemas help organize, validate, and store data consistently.