Bird
Raised Fist0
NestJSframework~20 mins

Schema definition in NestJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
NestJS Schema Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this NestJS schema validation?
Given this schema and input, what will be the validation result?
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User extends Document {
  @Prop({ required: true })
  name: string;

  @Prop({ default: 18 })
  age: number;
}

const UserSchema = SchemaFactory.createForClass(User);

// Input data:
const input = { name: 'Alice' };
AValidation fails because age is missing
BValidation passes, age is set to 18 by default
CValidation passes, age is undefined
DValidation fails because name is missing
Attempts:
2 left
💡 Hint
Check the @Prop decorator options for default and required
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a nested schema in NestJS?
You want to define a nested Address schema inside a User schema. Which code snippet is correct?
A
class Address {
  @Prop() street: string;
  @Prop() city: string;
}

@Schema()
class User {
  @Prop({ type: () => Address }) address: Address;
}
B
@Schema()
class Address {
  @Prop() street: string;
  @Prop() city: string;
}

@Schema()
class User {
  @Prop({ type: Address }) address: Address;
}
C
@Schema()
class Address {
  @Prop() street: string;
  @Prop() city: string;
}

@Schema()
class User {
  @Prop({ type: () => Address }) address: Address;
}
D
class Address {
  @Prop() street: string;
  @Prop() city: string;
}

@Schema()
class User {
  @Prop({ type: Address }) address: Address;
}
Attempts:
2 left
💡 Hint
Nested schemas require both classes to be decorated with @Schema and use a function for type.
🔧 Debug
advanced
2:00remaining
Why does this NestJS schema throw a runtime error?
This schema code throws an error when creating a Product document. What is the cause?
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Product extends Document {
  @Prop()
  name: string;

  @Prop({ type: Number, required: true })
  price: number;
}

export const ProductSchema = SchemaFactory.createForClass(Product);

// Error: Missing required property 'price' when creating a Product document
AThe 'price' property is missing a default value and is required, causing error if not provided
BThe @Prop decorator must not include 'type' when using TypeScript types
CThe class should not extend Document when using SchemaFactory
DThe 'name' property is missing 'required: true' causing schema validation failure
Attempts:
2 left
💡 Hint
Check which properties are required and if defaults exist
❓ state_output
advanced
2:00remaining
What is the value of 'createdAt' after saving this schema?
Given this schema with timestamps enabled, what will be the value of 'createdAt' after saving a new document?
NestJS
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema({ timestamps: true })
export class Article extends Document {
  @Prop() title: string;
}

const ArticleSchema = SchemaFactory.createForClass(Article);

// After saving a new Article with title 'Hello', what is article.createdAt?
ANull because timestamps are disabled by default
BUndefined because 'createdAt' is not defined in the class
CA string with the ISO date format
DA Date object representing the creation time
Attempts:
2 left
💡 Hint
Timestamps option automatically adds createdAt and updatedAt fields as Date objects
🧠 Conceptual
expert
2:00remaining
Which option best explains the purpose of SchemaFactory in NestJS?
Why does NestJS use SchemaFactory.createForClass instead of directly using Mongoose schemas?
AIt generates a Mongoose schema from a decorated TypeScript class, enabling decorators to define schema properties
BIt replaces the need for Mongoose entirely by providing a custom schema system
CIt compiles TypeScript classes into JavaScript functions for faster runtime performance
DIt automatically connects the schema to the database without manual model creation
Attempts:
2 left
💡 Hint
Think about how decorators and classes relate to Mongoose schemas

Practice

(1/5)
1. What is the main purpose of using @Schema() in NestJS?
easy
A. To define the structure and rules of a data model
B. To create a new controller
C. To handle HTTP requests
D. To style components

Solution

  1. Step 1: Understand the role of @Schema()

    @Schema() is used to define how data should be structured and validated in NestJS models.
  2. Step 2: Compare with other options

    Creating controllers, handling HTTP requests, and styling components are unrelated to schema definition.
  3. Final Answer:

    To define the structure and rules of a data model -> Option A
  4. Quick 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
A. @Prop() title: number;
B. @Prop() title: string;
C. @Prop() title = 123;
D. @Prop() title: boolean;

Solution

  1. Step 1: Identify the correct type for a string property

    The property title should be of type string to hold text data.
  2. Step 2: Check the syntax of @Prop()

    The correct syntax is @Prop() title: string; which declares a string property.
  3. Final Answer:

    @Prop() title: string; -> Option B
  4. Quick 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:
@Schema()
export class Book {
  @Prop()
  author: string;

  @Prop({ required: true })
  pages: number;
}

What happens if you try to save a Book without pages?
medium
A. The save will throw a syntax error
B. The save will succeed and pages will be undefined
C. The save will succeed and pages will default to 0
D. The save will fail because pages is required

Solution

  1. Step 1: Understand the required: true option

    The pages property is marked as required, so it must be provided when saving.
  2. Step 2: Predict behavior when missing required property

    Omitting pages causes validation to fail and the save operation to be rejected.
  3. Final Answer:

    The save will fail because pages is required -> Option D
  4. Quick 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
A. No error, this is correct
B. Missing @Schema() decorator
C. The type in @Prop() does not match the property type
D. Property name cannot be 'age'

Solution

  1. Step 1: Compare @Prop() type and property type

    The decorator says type: String but the property is declared as number.
  2. Step 2: Understand type mismatch consequences

    This mismatch can cause runtime errors or incorrect schema behavior.
  3. Final Answer:

    The type in @Prop() does not match the property type -> Option C
  4. Quick 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
A. @Schema() export class Product { @Prop({ required: true }) name: string; @Prop() price?: number; @Prop({ default: true }) inStock: boolean; }
B. @Schema() export class Product { @Prop() name: string; @Prop({ required: true }) price: number; @Prop({ default: false }) inStock: boolean; }
C. @Schema() export class Product { @Prop({ required: true }) name: number; @Prop() price: string; @Prop({ default: true }) inStock: boolean; }
D. @Schema() export class Product { @Prop({ required: true }) name: string; @Prop({ default: 0 }) price: number; @Prop() inStock: boolean; }

Solution

  1. Step 1: Define required name as string

    Use @Prop({ required: true }) name: string; to make name mandatory.
  2. Step 2: Define optional price as number

    Use @Prop() price?: number; to allow price to be optional.
  3. Step 3: Define inStock with default true

    Use @Prop({ default: true }) inStock: boolean; to set default value.
  4. Final Answer:

    Schema with required name (string), optional price (number), and inStock default true -> Option A
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard