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.
Schema definition in NestJS
Introduction
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
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);
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);
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.
Practice
1. What is the main purpose of using
@Schema() in NestJS?easy
Solution
Step 1: Understand the role of
@Schema()@Schema()is used to define how data should be structured and validated in NestJS models.Step 2: Compare with other options
Creating controllers, handling HTTP requests, and styling components are unrelated to schema definition.Final Answer:
To define the structure and rules of a data model -> Option AQuick Check:
Schema decorator defines data structure [OK]
Hint: Remember: @Schema() sets data shape, not controllers or styles [OK]
Common Mistakes:
- Confusing @Schema() with controller decorators
- Thinking @Schema() handles HTTP logic
- Mixing schema with UI styling
2. Which of the following is the correct way to define a string property named
title in a NestJS schema?easy
Solution
Step 1: Identify the correct type for a string property
The propertytitleshould be of typestringto hold text data.Step 2: Check the syntax of @Prop()
The correct syntax is@Prop() title: string;which declares a string property.Final Answer:
@Prop() title: string; -> Option BQuick Check:
String property uses type string [OK]
Hint: Use @Prop() with correct TypeScript type for properties [OK]
Common Mistakes:
- Using wrong types like number or boolean for string data
- Assigning values instead of declaring types
- Missing @Prop() decorator
3. Given this schema snippet:
What happens if you try to save a Book without
@Schema()
export class Book {
@Prop()
author: string;
@Prop({ required: true })
pages: number;
}What happens if you try to save a Book without
pages?medium
Solution
Step 1: Understand the
Therequired: trueoptionpagesproperty is marked as required, so it must be provided when saving.Step 2: Predict behavior when missing required property
Omittingpagescauses validation to fail and the save operation to be rejected.Final Answer:
The save will fail becausepagesis required -> Option DQuick Check:
Required props must be present [OK]
Hint: Required props block save if missing [OK]
Common Mistakes:
- Assuming missing required props default silently
- Confusing validation errors with syntax errors
- Ignoring the required option in @Prop()
4. Identify the error in this schema definition:
@Schema()
export class User {
@Prop({ type: String })
age: number;
}medium
Solution
Step 1: Compare @Prop() type and property type
The decorator saystype: Stringbut the property is declared asnumber.Step 2: Understand type mismatch consequences
This mismatch can cause runtime errors or incorrect schema behavior.Final Answer:
The type in @Prop() does not match the property type -> Option CQuick Check:
Decorator type must match property type [OK]
Hint: Match @Prop() type with property type exactly [OK]
Common Mistakes:
- Using wrong type in @Prop() options
- Ignoring type mismatch warnings
- Assuming property name causes errors
5. How would you define a schema for a
Product with a required name (string), optional price (number), and a default inStock (boolean) set to true?hard
Solution
Step 1: Define required
Usenameas string@Prop({ required: true }) name: string;to makenamemandatory.Step 2: Define optional
Usepriceas number@Prop() price?: number;to allowpriceto be optional.Step 3: Define
UseinStockwith default true@Prop({ default: true }) inStock: boolean;to set default value.Final Answer:
Schema with required name (string), optional price (number), and inStock default true -> Option AQuick Check:
Required, optional, default props set properly [OK]
Hint: Use required, optional ?, and default in @Prop() [OK]
Common Mistakes:
- Mixing types for properties
- Forgetting to mark required props
- Setting wrong default values
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
