Getting Started with NestJS and MongoDB


In this article, we will be making an API server using NestJS and MongoDB (with the help of Mongoose)

We are going to create Cat and Owner model and link them together.

For the Cat and Owner relation, we explore two cases:

- A cat can have one owner

- A cat can have many owners

Note: In this article, we are not linking controllers and services. If any of you request it, I’ll write it when time permits.

Without further ado, let’s get started.

If you haven’t intalled NestJS CLI tool

npm i -g @nestjs/cli


Create project

nest new project-name


Install dependencies

yarn add @nestjs/mongoose mongoose


Import into AppModule

app.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
@Module({
  imports: [MongooseModule.forRoot('mongodb://localhost/nest')],
})
export class AppModule {}


Generate module

nest generate module [module name]


example

nest generate module cat


Generate Controller

nest generate controller [controller name]


example

nest generate controller cat


Generate Service

nest generate service cat


Add mongoose schema Model

/cat/schemas/cat.schema.ts

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type CatDocument = Cat & Document;
@Schema({ timestamps: true })
export class Cat {
  @Prop({ required: true })
  name: string;
  @Prop()
  age: number;
  @Prop()
  breed: string;
}
export const CatSchema = SchemaFactory.createForClass(Cat);


Customizing toJSON()

schema.path('name').get(function (v) {
  return v + ' is my name';
});
schema.set('toJSON', { getters: true, virtuals: false });


Relations to other Model

import * as mongoose from 'mongoose';
import { Owner } from '../owners/schemas/owner.schema';
// inside the class definition
@Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' })
owner: Owner;


Multiple owners

@Prop({ type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Owner' }] })
owner: Owner[];


Add to module

/cat/cat.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsController } from './cat.controller';
import { CatsService } from './cat.service';
import { Cat, CatSchema } from './schemas/cat.schema';
@Module({

    imports: [MongooseModule.forFeature([{ name: Cat.name, schema:
  CatSchema }])],

  controllers: [CatsController],
  providers: [CatsService],
    exports: [Cat],
})
export class CatModule {}


Inject Cat model into CatService

cats.service.ts

import { Model } from 'mongoose';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Cat, CatDocument } from './schemas/cat.schema';
import { CreateCatDto } from './dto/create-cat.dto';
@Injectable()
export class CatsService {

    constructor(@InjectModel(Cat.name) private catModel:
  Model<CatDocument>) {}

  async create(createCatDto: CreateCatDto): Promise<Cat> {
    const createdCat = new this.catModel(createCatDto);
    return createdCat.save();
  }
  async findAll(): Promise<Cat[]> {
    return this.catModel.find().exec();
  }
}


Run project

yarn start 


Credit Source : Kruy Vanna
Previous Post Next Post