0
0
NestJSframework~30 mins

Schema definition in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
NestJS Schema Definition with Mongoose
📖 Scenario: You are building a simple NestJS application to manage a list of books in a library. Each book has a title, author, and number of pages.
🎯 Goal: Create a Mongoose schema in NestJS to define the structure of the Book documents stored in MongoDB.
📋 What You'll Learn
Create a Mongoose schema named BookSchema with fields title, author, and pages.
Set title and author as strings and pages as a number.
Add a configuration variable maxPages to limit the maximum number of pages.
Use the schema to create a model named Book.
💡 Why This Matters
🌍 Real World
Defining schemas is essential when working with databases in NestJS to ensure data is structured and validated correctly.
💼 Career
Understanding schema definition and validation is a key skill for backend developers working with NestJS and MongoDB.
Progress0 / 4 steps
1
Create the initial Book schema
Create a constant called BookSchema using new Schema from mongoose. Define fields title and author as strings, and pages as a number.
NestJS
Need a hint?

Use new Schema({ title: String, author: String, pages: Number }) to define the schema.

2
Add a maxPages configuration variable
Add a constant named maxPages and set it to 1000 to represent the maximum allowed pages for a book.
NestJS
Need a hint?

Simply write export const maxPages = 1000; below the schema.

3
Add page limit validation to the schema
Update BookSchema to add a max validator on the pages field using the maxPages constant.
NestJS
Need a hint?

Change pages: Number to pages: { type: Number, max: maxPages }.

4
Create and export the Book model
Import model from mongoose and create a constant Book by calling model with 'Book' and BookSchema. Export the Book constant.
NestJS
Need a hint?

Use export const Book = model('Book', BookSchema); after importing model.