CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nestjs--mongoose

NestJS module that provides seamless integration between NestJS and Mongoose ODM for MongoDB database operations

80

1.02x
Quality

Pending

Does it follow best practices?

Impact

80%

1.02x

Average score across 10 eval scenarios

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

NestJS Mongoose

NestJS Mongoose provides seamless integration between NestJS and Mongoose ODM for MongoDB database operations. It offers a comprehensive set of decorators, services, and utilities that enable developers to build robust, type-safe MongoDB applications within the NestJS framework ecosystem.

Package Information

  • Package Name: @nestjs/mongoose
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @nestjs/mongoose mongoose

Core Imports

import { MongooseModule, InjectModel, Schema, Prop } from '@nestjs/mongoose';
import { DynamicModule } from '@nestjs/common';
import { Connection, ConnectOptions, MongooseError } from 'mongoose';

For CommonJS:

const { MongooseModule, InjectModel, Schema, Prop } = require('@nestjs/mongoose');

Basic Usage

import { Module, Injectable } from '@nestjs/common';
import { MongooseModule, InjectModel, Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
import { Model } from 'mongoose';

// Define a schema
@Schema()
export class User {
  @Prop({ required: true })
  name: string;

  @Prop()
  email: string;

  @Prop({ default: Date.now })
  createdAt: Date;
}

export const UserSchema = SchemaFactory.createForClass(User);

// Module configuration
@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nest'),
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])
  ],
  providers: [UserService],
})
export class AppModule {}

// Service using the model
@Injectable()
export class UserService {
  constructor(@InjectModel(User.name) private userModel: Model<User>) {}

  async create(createUserDto: any): Promise<User> {
    const createdUser = new this.userModel(createUserDto);
    return createdUser.save();
  }

  async findAll(): Promise<User[]> {
    return this.userModel.find().exec();
  }
}

Architecture

NestJS Mongoose is built around several key components:

  • Module System: MongooseModule provides configuration for database connections and model registration
  • Schema Decorators: @Schema(), @Prop(), and @Virtual() enable declarative schema definition
  • Dependency Injection: @InjectModel() and @InjectConnection() integrate with NestJS DI system
  • Factory Classes: SchemaFactory and related factories generate Mongoose schemas from decorated classes
  • Validation Pipes: Built-in pipes for MongoDB ObjectId validation and parsing
  • Connection Management: Support for multiple database connections and async configuration

Capabilities

Module Configuration

Core module classes for setting up MongoDB connections and registering models in NestJS applications.

class MongooseModule {
  static forRoot(uri: string, options?: MongooseModuleOptions): DynamicModule;
  static forRootAsync(options: MongooseModuleAsyncOptions): DynamicModule;
  static forFeature(models?: ModelDefinition[], connectionName?: string): DynamicModule;
  static forFeatureAsync(factories?: AsyncModelFactory[], connectionName?: string): DynamicModule;
}

interface MongooseModuleOptions extends ConnectOptions {
  uri?: string;
  retryAttempts?: number;
  retryDelay?: number;
  connectionName?: string;
  connectionFactory?: (connection: any, name: string) => any;
  connectionErrorFactory?: (error: MongooseError) => MongooseError;
  lazyConnection?: boolean;
  onConnectionCreate?: (connection: Connection) => void;
  verboseRetryLog?: boolean;
}

Module Configuration

Schema Definition

Decorators and utilities for defining MongoDB schemas using TypeScript classes with full type safety.

function Schema(options?: SchemaOptions): ClassDecorator;

function Prop(options?: PropOptions): PropertyDecorator;

function Virtual(options?: VirtualOptions): PropertyDecorator;

Schema Definition

Dependency Injection

Decorators for injecting Mongoose models and connections into NestJS services and controllers.

function InjectModel(model: string, connectionName?: string): ParameterDecorator;

function InjectConnection(name?: string): ParameterDecorator;

Dependency Injection

Schema Factories

Factory classes for generating Mongoose schemas and definitions from decorated TypeScript classes.

class SchemaFactory {
  static createForClass<TClass>(target: Type<TClass>): mongoose.Schema<TClass>;
}

class DefinitionsFactory {
  static createForClass(target: Type<unknown>): mongoose.SchemaDefinition;
}

Schema Factories

Validation Pipes

Pre-built pipes for validating and parsing MongoDB ObjectIds in request parameters and body data.

class IsObjectIdPipe implements PipeTransform {
  transform(value: string): string;
}

class ParseObjectIdPipe implements PipeTransform {
  transform(value: string): Types.ObjectId;
}

Validation Pipes

Utility Functions

Helper functions for generating dependency injection tokens and handling connection retry logic.

function getModelToken(model: string, connectionName?: string): string;

function getConnectionToken(name?: string): string;

function raw(definition: Record<string, any>): Record<string, any>;

Utility Functions

Core Types

interface ModelDefinition {
  name: string;
  schema: any;
  collection?: string;
  discriminators?: DiscriminatorOptions[];
}

interface AsyncModelFactory {
  name: string;
  collection?: string;
  discriminators?: DiscriminatorOptions[];
  imports?: any[];
  useFactory: (...args: any[]) => ModelDefinition['schema'] | Promise<ModelDefinition['schema']>;
  inject?: any[];
}

interface MongooseModuleAsyncOptions {
  connectionName?: string;
  imports?: any[];
  useExisting?: Type<MongooseOptionsFactory>;
  useClass?: Type<MongooseOptionsFactory>;
  useFactory?: (...args: any[]) => Promise<MongooseModuleFactoryOptions> | MongooseModuleFactoryOptions;
  inject?: any[];
}

type PropOptions = Partial<mongoose.SchemaDefinitionProperty> | mongoose.SchemaType;

interface VirtualOptions {
  options?: VirtualTypeOptions;
  subPath?: string;
  get?: (...args: any[]) => any;
  set?: (...args: any[]) => any;
}

Constants

const DEFAULT_DB_CONNECTION = 'DatabaseConnection';
const MONGOOSE_MODULE_OPTIONS = 'MongooseModuleOptions';
const MONGOOSE_CONNECTION_NAME = 'MongooseConnectionName';
const RAW_OBJECT_DEFINITION = 'RAW_OBJECT_DEFINITION';

Error Handling

class CannotDetermineTypeError extends Error {
  constructor(hostClass: string, propertyKey: string);
}
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@nestjs/mongoose@11.0.x
Publish Source
CLI
Badge
tessl/npm-nestjs--mongoose badge