1.0.0 • Published 2 years ago

nestjs-mongo-object-id v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

nestjs-object-id

npm

MongoDB ObjectId validator and parser for NestJS

Installation

npm install nestjs-object-id

Usage

@IsObjectId()

@IsObjectId() is a decorator for validating MongoDB Object IDs in DTOs. Here is an example along with commonly used IsString and IsNotEmpty from class-validator package.

import { IsObjectId } from 'nestjs-object-id';
import { IsString, IsNotEmpty } from 'class-validator';

class UpdatePostDTO {
    @IsObjectId()
    authorId: string;

    @IsString()  
    @IsNotEmpty()
    title: string;
}

IsObjectIdPipe

IsObjectIdPipe is a pipe for validating MongoDB Object IDs in route parameters.

import { IsObjectIdPipe } from 'nestjs-object-id';

@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @Get(':id')
  findOne(@Param('id', IsObjectIdPipe) id: string) {
    return this.postsService.findOne(id);
  }
}

ParseObjectIdPipe

ParseObjectIdPipe extends the functionality of IsObjectIdPipe by converting string parameters into Types.ObjectId instances.

import { ParseObjectIdPipe } from 'nestjs-object-id';
import { Types } from 'mongoose';

@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @Get(':id')
  findOne(@Param('id', ParseObjectIdPipe) id: Types.ObjectId) {
    return this.postsService.findOne(id);
  }
}

Author

Vladyslav Braslavskyi GitHub

License

Licensed under the MIT License - see the LICENSE file for details.