[Solved] How do you manage interfaces/models/validation classes in Nest JS? – Mongodb

by
Ali Hasan
dto mongodb mongoose mongoose-schema nestjs

The Problem:

In NestJS, managing interfaces, models, and validation classes can be challenging due to boilerplate code. Typically, interfaces define model structures, DTO classes handle validation, and Mongoose schemas mirror interfaces. Modifying document structures requires updates in all three places, leading to code duplication. Additionally, validation is performed both on schemas and DTOs, creating redundancy. The goal is to find an efficient solution that eliminates code duplication and streamlines validation while maintaining data integrity.

The Solutions:

Solution 1: Using NestJS Mongoose Schema Decorators for Validation

NestJS provides the `@nestjs/mongoose` package that enables you to define Mongoose schemas using TypeScript classes and decorators. It allows you to use one DTO class for both defining the schema and handling validation by decorating class properties with `class-validator` decorators. An example of such a class is provided below:

“`typescript
import { Prop, Schema, SchemaFactory } from ‘@nestjs/mongoose’;
import { IsNotEmpty, IsString, IsEmail } from ‘class-validator’;
import { HydratedDocument } from ‘mongoose’;

export type UserDocument = HydratedDocument;

@Schema()
export class User {
@IsNotEmpty()
@IsString()
@Prop()
name: string;

@IsNotEmpty()
@IsEmail()
@Prop({ required: true, unique: true })
email: string;

@IsNotEmpty()
@IsString()
@Prop()
password: string;
}

export const UserSchema = SchemaFactory.createForClass(User);


This class serves as both a Mongoose schema and handles validation. By using this approach, you can eliminate the need for separate schema and DTO classes, reducing boilerplate code and simplifying your codebase.

Q&A

Is it possible to use one DTO class in NestJS to implement both Mongoose schema definition and validation?

Yes, NestJS offers a package called @nestjs/mongoose which allows you to define Mongoose schema using Typescript classes and decorators. The same DTO class used to define the Mongoose schema can also be used to define validation rules using class-validator as well.

How can I use the same class for both mongoose schema definition and request body validation in NestJS but have additional DTOs for specific CRUD operations?

Use the Omit operator to exclude any properties that are exclusive to the schema in the create DTO, and use the Partial operator to make properties optional in the update DTO.

How can I avoid having to change code in three different places when making changes to the structure of my documents in NestJS?

Use an interface that describes the model, use Schema classes that implement the interface and use DTOs that implement the same interface to do validation.

Video Explanation:

The following video, titled "Realtime Chat App with React, Node.js, Socket.io and MongoDB ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Hey Coders, In this video we will create a realtime chat app with react, node.js and socket.io with mongodb and express.