docs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10
NestJS module that provides seamless integration between NestJS and Mongoose ODM for MongoDB database operations
Agent Success
Agent success rate when using this tile
80%
Improvement
Agent success rate improvement when using this tile compared to baseline
1.01x
Baseline
Agent success rate without this tile
79%
tessl install tessl/npm-nestjs--mongoose@11.0.0NestJS 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.
npm install @nestjs/mongoose mongooseimport { 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');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();
}
}NestJS Mongoose is built around several key components:
MongooseModule provides configuration for database connections and model registration@Schema(), @Prop(), and @Virtual() enable declarative schema definition@InjectModel() and @InjectConnection() integrate with NestJS DI systemSchemaFactory and related factories generate Mongoose schemas from decorated classesCore 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;
}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;Decorators for injecting Mongoose models and connections into NestJS services and controllers.
function InjectModel(model: string, connectionName?: string): ParameterDecorator;
function InjectConnection(name?: string): ParameterDecorator;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;
}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;
}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>;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;
}const DEFAULT_DB_CONNECTION = 'DatabaseConnection';
const MONGOOSE_MODULE_OPTIONS = 'MongooseModuleOptions';
const MONGOOSE_CONNECTION_NAME = 'MongooseConnectionName';
const RAW_OBJECT_DEFINITION = 'RAW_OBJECT_DEFINITION';class CannotDetermineTypeError extends Error {
constructor(hostClass: string, propertyKey: string);
}