DEV Community

Nayden Gochev
Nayden Gochev

Posted on • Edited on

NestJS + Mongo + Typegoose

Currently there are 3 options to use Mongo with Node (and NestJS).

We will look into each and every one of them and I will provide an example how you can use MongoDB in your NestJS application in a headache free way.

1) NestJS + Mongoose where maybe the best tutorial I have found is here https://scotch.io/tutorials/building-a-modern-app-using-nestjs-mongodb-and-vuejs the issue is that I hate the fact I had to write the schema definitions and the typescript interfaces. If you are fine with writing everything 2 times ones the Schema and ones the Document as Typescript Interface maybe this is the best way to go !

2) NestJS + TypeORM where you can actually use TypeORM with MongoDB, however I do not recomment this if you want to learn more I would ask you to read this blog post https://medium.com/articode/typeorm-mongodb-review-8855903228b1

3) NestJS + Typegoose — basically what it does is it uses your domain objects to get the schema from them. And this is what this post is all about. There is a lot of documentation how you can achieve that, however I didn’t like most of it, it just looked like too much code. On top of that ALL tutorials ALWAYS include using of a DTO class and I don’t see a reason to use DTO classes at all in 99% of the cases. DTOs are great, don’t get me wrong, there are many pros of using DTOs, but none of the tutorials on the internet actually explains why they want DTOs and in fact none of them need DTOs so I would like to write the most easy straightforward way with NestJS + MongoDB + and TypeGoose.

So first of all we will install NestJS CLI, NestJS is very, very similar to Angular and even if you don't like angular, trust me you will like NestJS, since I am actually the same! Btw great beginners tutorial for NestJS you can read here find https://scotch.io/tutorials/getting-started-with-nestjs

So lets start by creating the NestJS app

npm i -g @nestjs/cli

Then create a NestJS project.

nest new nestjspoc-nest
cd nestjspoc-nest
// start the application using nodemon
npm run start:dev
Enter fullscreen mode Exit fullscreen mode

open browser to localhost:3000 to verify hello world is displayed.

Ok we will create a simple Service and Controller in a Module, lets say our applications will do something with Users and we will want UserModule which will hold the User domain objects, User services and user controllers.

nest generate module user
nest generate service user
nest generate controller user
Enter fullscreen mode Exit fullscreen mode

Now you should have a folder which has UserModule, UserService and UserController.
Which are almost empty.

Nest we will use nestjs-typegoose because it just makes everything even easier.

npm install — save nestjs-typegoose

the typegoose has several peer dependencies so we need to install them as well. The two nestjs dependencies we already have but we need the other two.

"@typegoose/typegoose": "^6.0.0",
"@nestjs/common": "^6.3.1",
"@nestjs/core": "^6.3.1",
"mongoose": "^5.5.13"
Enter fullscreen mode Exit fullscreen mode

Ones done your package.json should look like this:

{
  "name": "nestjspoc",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "license": "MIT",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "tslint -p tsconfig.json -c tslint.json",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@nestjs/common": "^6.7.2",
    "@nestjs/core": "^6.7.2",
    "@nestjs/platform-express": "^6.7.2",
    "nestjs-typegoose": "^7.0.0",
    "rimraf": "^3.0.0",
    "rxjs": "^6.5.3",
    "@typegoose/typegoose": "^6.0.0",
    "mongoose": "^5.5.13"
  },
  "devDependencies": {
    "@nestjs/cli": "^6.9.0",
    "@nestjs/schematics": "^6.7.0",
    "@nestjs/testing": "^6.7.1",
    "@types/express": "^4.17.1",
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.5",
    "@types/supertest": "^2.0.8",
    "jest": "^24.9.0",
    "prettier": "^1.18.2",
    "supertest": "^4.0.2",
    "ts-jest": "^24.1.0",
    "ts-loader": "^6.1.1",
    "ts-node": "^8.4.1",
    "tsconfig-paths": "^3.9.0",
    "tslint": "^5.20.0",
    "typescript": "^3.6.3"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".spec.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "coverageDirectory": "./coverage",
    "testEnvironment": "node"
  }
}
Enter fullscreen mode Exit fullscreen mode

Well this is the setup, let’s write some code.

Create your domain object user in a file user.ts for example :

import {prop, Typegoose} from '@typegoose/typegoose';

export class User extends Typegoose {
    @prop()
    name?: string;
}
Enter fullscreen mode Exit fullscreen mode

You see the @prop() yup you need this. You can learn more about validations and what you can do in the typegoose documentation.
Then lets create or update our UserService class.

import {Injectable} from '@nestjs/common';
import {User} from './domain/user';
import {InjectModel} from 'nestjs-typegoose';
import {ReturnModelType} from '@typegoose/typegoose';

@Injectable()
export class UserService {
    constructor(@InjectModel(User) private readonly userModel: ReturnModelType<typeof User>) {
    }

    async createCustomUser(user: User) {
        const createdUser = new this.userModel(user);
        return await createdUser.save();
    }

    async listUsers(): Promise<User[] | null> {
        return await this.userModel.find().exec();
    }
}
Enter fullscreen mode Exit fullscreen mode

Ok the first magic is actually here !

You may notice the line @InjectModel(User) private readonly userModel: ReturnModelType, this will give us a userModel that we can use for our User type.

The createCustomUser and listUsers use this userModel and I believe it is all clear HOW :)

Next update our UserController.

import {Body, Controller, Get, Post} from '@nestjs/common';
import {UserService} from './user.service';
import {User} from './domain/user';

@Controller('user')
export class UserController {
    constructor(private readonly userService: UserService) { }

    @Get('listusers')
    async listUsers(): Promise<User[] | null> {
        return await this.userService.listUsers();
    }

    @Post('createuser')
    async createUser(@Body() cat: User): Promise<User> {
        return await this.userService.createCustomUser(cat);
    }
}
Enter fullscreen mode Exit fullscreen mode

Nothing fancy here, we just inject our Service and we call our two methods.

Next - a bit more magic !

There are two magic lines more, that you need to add to your UserModule and AppModule

On the UserModule definition we need this line imports: [TypegooseModule.forFeature([User])]

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import {User} from './domain/user';
import {TypegooseModule} from 'nestjs-typegoose';

@Module({
  imports: [TypegooseModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

And on the AppModule we need the Mongoose configuraiton of the MongoDB connection string imports: imports: [TypegooseModule.forRoot(‘mongodb://localhost:27017/nest’),
UserModule],

import {Module} from '@nestjs/common';
import {AppController} from './app.controller';
import {AppService} from './app.service';
import {UserModule} from './user/user.module';
import {TypegooseModule} from 'nestjs-typegoose';

@Module({
    imports: [TypegooseModule.forRoot('mongodb://localhost:27017/nest'),
        UserModule],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule {
}
Enter fullscreen mode Exit fullscreen mode

And yes you need MongoDB to be running ;)

Well that’s it!

Testing it - the monkey way !

Create a user:

curl -X POST http://localhost:3000/user/createuser 
-H ‘Content-Type: application/json’ -d ‘{ “name”: “Nayden Gochev” }’
Enter fullscreen mode Exit fullscreen mode

And you will receive

{“_id”:”5dc00795d9a25df587a1e5f9",”name”:”Nayden Gochev”,”__v”:0}
Enter fullscreen mode Exit fullscreen mode

List all users:

curl -X GET http://localhost:3000/user/listusers
Enter fullscreen mode Exit fullscreen mode

Missing bits !

What is missing ? Validation, Security and Testing of course, all of this — next time ;) now was the nest time.

Source code

the full source code can be download here:
https://github.com/gochev/nest-js-poc-mongodb

I am a Java developer with a lot of Spring knowledge, but recently I had to write some JavaScript even if I don’t want to, so maybe that explains why I like NestJS, and yes this done in Java and Spring is a lot easier https://github.com/gochev/spring-mvc-poc-mongodb but it is fun with NestJS right ? :)

Top comments (6)

Collapse
 
maki profile image
Maki

Thank you for writing this! I couldn't find anything like it. It's really really clear to me now and I think I'm gonna migrate to this method from the original method on the docs for the huge web server I'm building. This should be in the Nest docs imo

Collapse
 
gochev profile image
Nayden Gochev

haha I am glad it was helpful :) yeah I spend some time making it work.. I just really hate to repeat stuff :)) and DRY is a MUST :)) :D

Collapse
 
vbarzana profile image
Victor A. Barzana

Nice article Nayden, you have a typo at the top: "I would ask you to write this blog post", I think you meant, "I would ask you to read this blog post"!!! Take care.

Collapse
 
gochev profile image
Nayden Gochev

haha thanks :))) nicely spotted ;)) i will edit it

Collapse
 
amiraatalla profile image
Amira Atalla • Edited

when I setup typegoose I have this problem

dev-to-uploads.s3.amazonaws.com/up...

Collapse
 
psytonik profile image
Anthony Fink

you have problem with version of typegoose, you need to downgrade typegoose to 5 from 6.