nestjs-typegoose-ng
v7.1.39
Published
A nestjs module wrapper for typegoose. Fork of nestjs-typegoose supports @nestjs/core 8.x.x and mongoose v6
Downloads
4
Readme
nestjs-typegoose-ng
Description
Fork of nestjs-typegoose supports @nestjs/core 8.x.x and mongoose v6
DO NOT USE IT IN PRODUCTION. WIP
Injects typegoose models for nest components and controllers. Typegoose equivalant for @nestjs/mongoose.
Using Typegoose removes the need for having a Model interface.
Installation
pnpm install --save nestjs-typegoose-ng
or
yarn add nestjs-typegoose-ng
Documentation
Here is the full documentation describing all basic and advanced features.
Basic usage
You can checkout the example
project for more details.
app.module.ts
import { Module } from "@nestjs/common";
import { TypegooseModule } from "nestjs-typegoose-ng";
import { CatsModule } from "./cat.module.ts";
@Module({
imports: [
TypegooseModule.forRoot("mongodb://localhost:27017/nest"),
CatsModule,
],
})
export class ApplicationModule {}
Create class that describes your schema
cat.model.ts
import { prop } from "@typegoose/typegoose";
import { IsString } from "class-validator";
export class Cat {
@IsString()
@prop({ required: true })
name: string;
}
Inject Cat for CatsModule
cat.module.ts
import { Module } from "@nestjs/common";
import { TypegooseModule } from "nestjs-typegoose-ng";
import { Cat } from "./cat.model";
import { CatsController } from "./cats.controller";
import { CatsService } from "./cats.service";
@Module({
imports: [TypegooseModule.forFeature([Cat])],
controllers: [CatsController],
providers: [CatsService],
})
export class CatsModule {}
Get the cat model in a service
cats.service.ts
import { Injectable } from "@nestjs/common";
import { InjectModel } from "nestjs-typegoose-ng";
import { Cat } from "./cat.model";
import { ReturnModelType } from "@typegoose/typegoose";
@Injectable()
export class CatsService {
constructor(
@InjectModel(Cat) private readonly catModel: ReturnModelType<typeof Cat>
) {}
async create(createCatDto: { name: string }): Promise<Cat> {
const createdCat = new this.catModel(createCatDto);
return await createdCat.save();
}
async findAll(): Promise<Cat[] | null> {
return await this.catModel.find().exec();
}
}
Finally, use the service in a controller!
cats.controller.ts
import { Controller, Get, Post, Body } from "@nestjs/common";
import { CatsService } from "./cats.service";
import { Cat } from "./cats.model.ts";
@Controller("cats")
export class CatsController {
constructor(private readonly catsService: CatsService) {}
@Get()
async getCats(): Promise<Cat[] | null> {
return await this.catsService.findAll();
}
@Post()
async create(@Body() cat: Cat): Promise<Cat> {
return await this.catsService.create(cat);
}
}
Requirements
- @typegoose/typegoose +9.4.0
- @nestjs/common +8.0.0
- @nestjs/core +8.0.0
- mongoose +6.1.5
License
nestjs-typegoose-ng is MIT licensed.