Skip to main content

NestJS + Mongo + Typegoose

The current state of Mongo with NestJS ( and Node) .

Currently you have 3 options to use Mongo with Node (and NestJS).

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 write 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 because of many reasons, 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 NEST + MongoDB + TypeGoose example.

So first of all we will install nestjs cli, NestJS is very, very similar to Angular and even if you dont like angular trust me you will like NestJS. Great beginners tutorial for NestJS you can read here find https://scotch.io/tutorials/getting-started-with-nestjs

So lets start:

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

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


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"
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"
  }
}
The ones we added manually are in bold.

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;
}

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) {
    }

    async createUser() {
        const user = new this.userModel();
        user.name = 'test nestjs2';
        return await user.save();
    }

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

    async listUsers(): Promise {
        return await this.userModel.find().exec();
    }
}

Ok the first magic here is @InjectModel(User) private readonly userModel: ReturnModelType , this will give us a userModel that we can use for our User type.

The createCustomUser and listUsers I believe are clear..

Next update our UserController.
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}


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

There are two fancy lines you need to add to your UserModule and AppModule 

On the UserModule add as an imports teh value 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 {}



And on the AppModule just Configure TypeGoose MongoDB connection string together with your UserModule (which is already added by the CLI).
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 {
}


And yes you need MongoDB to be running.

Well that's it!

Create a user:

curl -X POST http://localhost:3000/user/createuser -H 'Content-Type: application/json' -d '{ "name": "Nayden Gochev" }'

And you will receive

{"_id":"5dc00795d9a25df587a1e5f9","name":"Nayden Gochev","__v":0}

Also you can get the currently created users at any time :

curl -X GET http://localhost:3000/user/listusers

What else ? Validation ? Security and Tests of course  ! :), all of this - next time ;) now was the nest time.

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

About myself:
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 ? :)

Comments

Popular posts from this blog

Use Multiple JVM versions on Mac OS and Linux

Linux Download multiple Java versions and put them into /opt/ If you already have some JDK from ubuntu repo or etc not a big deal, just fix the paths bellow Register them as alternatives sudo update-alternatives --install /usr/bin/java java /opt/java-8-oracle/bin/java 1081 sudo update-alternatives --install /usr/bin/java java /opt/sap-machine-jdk-11.0.3/bin/java 1080 Edit your ~/.bashrc file alias java11='sudo update-alternatives --set java /opt/sapmachine-jdk-11.0.3/bin/java;export JAVA_HOME=/opt/sapmachine-jdk-11.0.3/' alias java8='sudo update-alternatives --set java /opt/java-8-oracle/bin/java;export JAVA_HOME=/usr/lib/java-8-oracle/' SAVE and start a new bash terminal execute java8 to use java8 java11 to use java11 the latest version you have set stays as system wide, but the JAVA_HOME is not :( you can put java8 or java11 as a last line in the bashrc but since it is sudo it will always require password when start and is not gr...

Hibernate Generic DAO.

When you use Hibernate and DAO pattern it is a good idea to use a Generic Base Dao. The fallowing code snippet contains GenericDAO that is a base class for all my DAO classes. This GenericDAO uses HibernateDaoSupport from Spring for its implementation if you want you can use JpaDaoSupport or JdbcDaoSupport in your projects. My Generic DAO interface looks like this : package org.joke.myproject.dao.base; import java.io.Serializable; import java.util.List; /** * @author Naiden Gochev * @param <E> * @param <PK> */ public interface GenericDao<E,PK  extends Serializable> {     PK save(E newInstance);     void update(E transientObject);     void saveOrUpdate(E transientObject);     void delete(E persistentObject);     E findById(PK id);     List<E> findAll();     List<E> f...

Patching a Maven library with your custom class.

Sometimes you use a library that has a bug. Or maybe it doesn’t has a bug but you want to change something. Of course if it is an open source you can get the sources… build them … with your change and so on. However this first takes a lot of time and second you need the sources. What you usually want .. is to just replace one class.. or few classes with something custom… maybe add a line .. or remove a line and so on. Yesterday… I had an issue with jboss-logging. The version I was using was 3.2.0Beta1 and it turns out that using this version and log4j2 2.0 final basically meant that no log is send to log4j2. The reason was a null pointer exception that was catched in jboss logging class called Log4j2Logger. The bug I submitted is here https://issues.jboss.org/browse/JBLOGGING-107 and it was fixed at the same day. However I will use it as an example since I didn’t knew when this will be fixed.. and I didn’t want to wait till it is fixed. So I was thinking what I want.. to take the j...