MongoDB Native Driver module for NestJS 8.x/9.x/10.x framework 😻
Tags: nestjs, mongodb, mongodbdriver, typescript
Published: 2022-05-16 18:58:54

In this post I will explain how to use my `MongoDB Node Driver` module for NestJS 😻.
For those unfamiliar or unfamiliar with [NestJS](https://nestjs.com/), it is a TypeScript Node.js framework that helps you build efficient and scalable enterprise-grade Node.js applications.


For those who have never used [MongoDB Driver] (https://www.mongodb.com/docs/drivers/node/current/) is the official package for MongoDB for Nodejs, but you can also use it in other programming languages   (see [here](https://www.mongodb.com/docs/drivers/) for more information on the drivers).


So let's get started by creating the NestJS app 😻.
Open terminal and install CLI for NestJS, if you already have it installed, skip this step.

```sh
$ npm i -g @nestjs/cli
```
### Then create a NestJS project

```sh
$ nest new app
$ cd app
// start the application
$ npm run start:dev
```

Open the browser on `localhost:3000` to verify that hello world is displayed.

then we create a `docker-compose.yml` file to create the service MongoDB

```yml
version: "3"

services:
  mongodb:
    image: mongo:latest
    environment:
      - MONGODB_DATABASE="nest"
    ports:
      - 27017:27017
```

for those who do not know what docker is I leave the link here for more information [Docker](https://www.docker.com/get-started).
Well now let's proceed with the package installation.

### Install MongoDbDriverModule and MongoDB dependencies

```sh
$ npm install --save nest-mongodb-driver mongodb
```

Set MongoDbDriverModule in AppModule

```typescript
import { Module } from '@nestjs/common';
import { MongoDbDriverModule } from 'nest-mongodb-driver';

@Module ({
   imports: [
    MongoDbDriverModule.forRoot({
      url: 'mongodb://localhost:27017/nest',
    }),
   ],
})
export class AppModule {}
```

Now let's create a REST API and call it users. We open the terminal and run the commands to create the module, the service and the controller for the users:

```sh
$ nest g mo users  # module
$ nest g s users   # service
$ nest g co users  # controller
```

`UsersModule`:

```typescript
import { Module } from '@nestjs/common';
import { UsersService } from './users.service';
import { UsersController } from './users.controller';

@Module({
  controllers: [UsersController],
  providers: [UsersService]
})
export class UsersModule {}

```

Before we start building our API, create the Data Transfer Objects (Dto) class to create the users

```typescript
import { IsEmail, IsNotEmpty, IsString } from "class-validator";

export class CreateUserDto {
    @Notempty()
    @IsString()
    firstName: string;

    @Notempty()
    @IsString()
    lastName: string;

    @Notempty()
    @IsString()
    @IsEmail()
    email: string;
}
```

Remember to install this package before creating the dto class for the upgrade.

``` sh
$ npm i @nestjs/mapped-types
```

Well, now to update the users data we extend the CreateUserDto class:

```typescript
import { PartialType } from '@nestjs/mapped-types';
import { CreateUserDto } from './create-user.dto';

export class UpdateUserDto extends PartialType(CreateUserDto){}
```

We then implement ours `UserService`:

```typescript
import {
  BadRequestException,
  HttpException,
  HttpStatus,
  Injectable,
  NotFoundException,
} from '@nestjs/common';
import { InjectClient } from 'nest-mongodb-driver';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { Db, ObjectId } from 'mongodb';

@Injectable()
export class UsersService {
  constructor(@InjectClient() private readonly db: Db) {}

  async findAll() {
    return await this.db.collection('users').find().toArray();
  }

  async findOne(id: string) {
    if (!ObjectId.isValid(id)) {
      throw new BadRequestException();
    }

    const result = await this.db.collection('users').findOne({
      _id: new ObjectId(id),
    });

    if (!result) {
      throw new NotFoundException();
    }

    return result;
  }

  async create(createUserDto: CreateUserDto) {
    try {
      return await this.db.collection('users').insertOne(createUserDto);
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }

  async update(id: string, updateUserDto: UpdateUserDto) {
    if (!ObjectId.isValid(id)) {
      throw new BadRequestException();
    }

    try {
      const result = this.db.collection('users').updateOne(
        {
          _id: new ObjectId(id),
        },
        {
          $set: {
            ...updateUserDto,
          },
        },
      );

      return result;
    } catch (err) {
      throw new HttpException(err, HttpStatus.BAD_REQUEST);
    }
  }

  async remove(id: string) {
    if (!ObjectId.isValid(id)) {
      throw new BadRequestException();
    }

    const result = await this.db.collection('users').deleteOne({
      _id: new ObjectId(id),
    });

    if (result.deletedCount === 0) {
      throw new NotFoundException();
    }
  }
}
```

`UsersController`:

```typescript
import { Controller, Get, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';

@Controller('/api/users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }

  @Get()
  findAll() {
    return this.usersService.findAll();
  }

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

  @Put(':id')
  update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
    return this.usersService.update(id, updateUserDto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.usersService.remove(id);
  }
}
```

well now we should have our API tested if everything works perfectly this commands from curl or whatever you prefer to use.
```
    $ curl -H 'content-type: application/json' -v -X GET http://127.0.0.1:3000/api/users  
    $ curl -H 'content-type: application/json' -v -X GET http://127.0.0.1:3000/api/users/:id 
    $ curl -H 'content-type: application/json' -v -X POST -d '{"firstName": "firstName #1", "lastName": "lastName #1", "email": "example@nest.it"}' http://127.0.0.1:3000/api/users 
    $ curl -H 'content-type: application/json' -v -X PUT -d '{"firstName": "firstName update #1", "lastName": "lastName update #1", "email": "example@nest.it}' http://127.0.0.1:3000/api/users/:id 
    $ curl -H 'content-type: application/json' -v -X DELETE http://127.0.0.1:3000/api/users/:id 
```

For more information on `MongoDB NodeJS Driver` see [here](https://www.mongodb.com/docs/drivers/node/current/).

This module is compatible with version 7.x of NestJS 😻.

That's it 😀 
Hope it can be useful in your projects.
For anything write me in the comments 😉