Follow us

May the source be with you!

Blog about the light side of the *.java

  • Home
  • Java
  • JavaFX
  • Spring
  • JavaScript
  • About me
  • Contacts
    • via mail
    • twitter
    • facebook
Home Archive for November 2019


Hello everyone,
in recent years I didn't have time to actually blog and the reason was not only the lack of time.
The real reason was that personal blogs are no longer this viable as ones were. In the current time, most people read medium or ghost or very development-aligned websites to get their content.

In the past years when this blog was created, dzone.com was actually a blog aggregator, where you put your blog and people can vote for it, in a way similar to Reddit. 
It was AWESOME having a front and back page and the blog links having a lot of votes sometimes made it to the front page. There was RSS for both pages and it was so so awesome and Javalobby was a forum back then. I don't know how these guys fcked up that much but shame. 

Anyway, all is over ... dzone is completely different, javalobby doesn't exist and to have a personal blog and just rely only on your Twitter or Reddit presence is just too much work for a developer, after all we have to also develop... not promote ourselves all the time. 

So because of the reasons above I am archiving my blog.

I might post sometimes to http://dev.to which I believe is the best medium alternative for developers blogging right now, it is basically Twitter and Reddit a like and you can follow me there at https://dev.to/gochev .


Also, my twitter is https://twitter.com/gochev and my LinkedIn is https://linkedin.com/in/gochev we can keep in touch with me there as well.



So long and thanks for all the fish!


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 ? :)
Subscribe to: Posts ( Atom )

ABOUT AUTHOR

Superhero with Java powers && Gamer && (Sci-Fi & Star Wars geek) && Bulgarian Java User Group Leader && nerds2nerds podcaster && (link: http://java.beer) java.beer guy ? this : null

Social

Twitter
Facebook

LATEST POSTS

  • Use Client Certificate Authentication with Java and RestTemplate
    As a follow up of the  http://gochev.blogspot.com/2019/04/convert-pfx-certificate-to-jks-p12-crt.html  we now have a keystore and a truststo...
  • Convert PFX certificate to JKS, P12, CRT
    I recently had to use a PFX certificate for client authentication (maybe another post will be coming) and for that reason I had to convert i...
  • 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 f...
  • 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...
  • Youtube video channel of the Bulgarian Java User Group
    Bad news everyone, as you already have noticed I do not have time to write blogs :( However I would recommend you to check and keep an ey...
  • 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 sourc...
  • RichFaces server-side paging with DataTable.
    Most of the component toolkits have build in support for server-side paging this days but in rest of the cases you need to customize a littl...
  • JSF, RichFaces, Spring, Hibernate – lets make development easy.
    The goal of this article is to show you how you can use Hibernate, Spring and JSF 1.2 in the most easiest way. Used technologies : ma...
  • spring-loaded rocks !
    Today I found spring loaded ( https://github.com/spring-projects/spring-loaded ) in short this is a java agent that enables class reloading...

Categories

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

What I read ?

  • Baeldung
  • Java Code Geeks
  • Vlad Mihalcea
  • Javarevisited
  • Pushing Pixels
  • Vanilla #Java
  • Antonio's Blog
  • Oracle Blogs | Oracle The Aquarium Blog
  • JavaWorld
  • blog@CodeFX
  • Jonathan Giles
  • JavaFX News, Demos and Insight // FX Experience
  • Eclipse Papercuts
  • Codedependent
  • Caffeine Induced Ramblings - Jasper Potts's Blog
  • Joshua Marinacci's Blog

Search This Blog

Blog Archive

  • November 2019 (2)
  • July 2019 (1)
  • April 2019 (2)
  • February 2019 (1)
  • January 2019 (1)
  • May 2016 (1)
  • October 2015 (1)
  • September 2015 (1)
  • June 2015 (2)
  • May 2015 (2)
  • February 2015 (1)
  • October 2014 (1)
  • July 2014 (2)
  • April 2014 (1)
  • June 2013 (1)
  • July 2011 (2)
  • May 2011 (1)
  • March 2011 (1)
  • July 2010 (1)
  • June 2010 (1)
  • October 2009 (3)
  • September 2009 (6)
  • August 2009 (9)
  • June 2009 (1)
Powered by Blogger.

Blog info

My photo
jNayden
View my complete profile

About us

Labels

  • .net
  • AboutMe
  • appengine
  • blogspot
  • conf
  • CV
  • gwt
  • java
  • java.javaee
  • javaee
  • javafx
  • javascript
  • other
  • photoshop
  • ria
  • spring

Advertisement

Popular Posts

    no image Use Client Certificate Authentication with Java and RestTemplate
    no image Convert PFX certificate to JKS, P12, CRT
    no image Use Multiple JVM versions on Mac OS and Linux
    no image Hibernate Generic DAO.
    no image Youtube video channel of the Bulgarian Java User Group
    Patching a Maven library with your custom class. Patching a Maven library with your custom class.
    RichFaces server-side paging with DataTable. RichFaces server-side paging with DataTable.
    no image JSF, RichFaces, Spring, Hibernate – lets make development easy.
    no image spring-loaded rocks !

FOLLOW US @ INSTAGRAM

About Me

  • Normal Link 01
  • Normal Link 02
  • Custom Menu 01
  • Custom Menu 02
  • Disclaimer
  • Terms
  • Policy
  • Home
  • About
  • Contact
  • Home
  • Features
  • _Multi DropDown
  • __DropDown 1
  • __DropDown 2
  • __DropDown 3
  • _ShortCodes
  • _SiteMap
  • _Error Page
  • Documentation
  • _Web
  • _Video
  • Download This Template

Menu Footer Widget

  • Home
  • About
  • Contact

Social Plugin

Tags

Advertisement

Responsive Advertisement
May the source be with you!

Popular Posts

java

Convert PFX certificate to JKS, P12, CRT

Use Client Certificate Authentication with Java and RestTemplate

Use Multiple JVM versions on Mac OS and Linux

Hibernate Generic DAO.

Copyright 2014 May the source be with you!.
Blogger Templates Designed by OddThemes