npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@robinwongm/nestjs-typegoose

v5.2.1

Published

A nestjs module wrapper for typegoose

Downloads

6

Readme

nestjs-typegoose

NPM npm version Build Status Coverage Status

Description

Injects typegoose models for nest components and controllers. Typegoose equivalant for @nestjs/mongoose.

Using Typegoose removes the need for having a Model interface.

Installation

npm install --save nestjs-typegoose

Basic usage

app.module.ts

import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';

@Module({
  imports: [TypegooseModule.forRoot('mongodb://localhost:27017/nest', { useNewUrlParser: true }), CatsModule],
})
export class ApplicationModule {}

Create class that extends Typegoose

cat.model.ts

import { prop, Typegoose } from 'typegoose';
import { IsString } from 'class-validator';

export class Cat extends Typegoose {
  @IsString()
  @prop({ required: true })
  name: string;
}

Inject Cat for CatsModule

cat.module.ts

import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';
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';
import { Cat } from './cat.model';
import { ModelType } from 'typegoose';

@Injectable()
export class CatsService {
  constructor(@InjectModel(Cat) private readonly catModel: ModelType<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';

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

Mongoose Schema Options

To add custom mongoose schema options you can simply change Typegoose.forFeature to the following format:

@Module({
  imports: [
    TypegooseModule.forFeature([{
      typegooseClass: Cat,
      schemaOptions: {
        collection: 'ADifferentCollectionNameForCats'
      }
    }])
  ]
})
export class CatsModule {}

Async Mongoose Schema Options

To provide asynchronous mongoose schema options (similar to nestjs mongoose implementation) you can use the TypegooseModule.forRootAsync

@Module({
  imports: [
    TypegooseModule.forAsyncRoot({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.getString('MONGODB_URI'),
        // ...typegooseOptions (Note: config is spread with the uri)
      }),
      inject: [ConfigService]
    })
  ]
})
export class CatsModule {}

Note: typegooseOptions with async

The typegooseOptions is spread with the uri. The uri is required!

You can also use a class with useClass

import { TypegooseOptionsFactory, TypegooseModuleOptions } from 'nestjs-typegoose';

class TypegooseConfigService extends TypegooseOptionsFactory {
  createTypegooseOptions(): Promise<TypegooseModuleOptions> | TypegooseModuleOptions {
    return {
      uri: 'mongodb://localhost/nest'
    }
  };
}

@Module({
  imports: [
    TypegooseModule.forAsyncRoot({
      useClass: TypegooseConfigService
    })
  ]
})
export class CatsModule {}

Or if you want to prevent creating another TypegooseConfigService class and want to use it from another imported module then use useExisting

@Module({
  imports: [
    TypegooseModule.forAsyncRoot({
      imports: [ConfigModule],
      useExisting: ConfigService,
    })
  ]
})
export class CatsModule {}

Multiple MongoDB Connections

To have multiple mongoDB connections one needs to add a connectionName string to forRoot and forFeature.

app.module.ts

import { Module } from '@nestjs/common';
import { TypegooseModule } from 'nestjs-typegoose';

@Module({
  imports: [TypegooseModule.forRoot('mongodb://localhost:27017/otherdb', { useNewUrlParser: true, connctionName: 'other-mongodb' }), CatsModule],
})
export class ApplicationModule {}

cat.module.ts

@Module({
  imports: [TypegooseModule.forFeature([Cat], 'other-mongodb')],
  controllers: [CatsController],
  providers: [CatsService]
})
export class CatsModule {}

And for forAsyncRoot add connectionName to the options as well.

@Module({
  imports: [
    TypegooseModule.forAsyncRoot({
      connectionName: 'other-mongodb',
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.getString('MONGODB_URI'),
        connectionName: config
        // ...typegooseOptions (Note: config is spread with the uri)
      }),
      inject: [ConfigService]
    })
  ]
})
export class CatsModule {}

Requirements

  1. Typegoose +5.2.1
  2. @nestjs/common +5.0.0
  3. @nestjs/core +5.0.0
  4. mongoose +5.1.1

License

nestjs-typegoose is MIT licensed.