0
# NestJS Mongoose
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: @nestjs/mongoose
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @nestjs/mongoose mongoose`
10
11
## Core Imports
12
13
```typescript
14
import { MongooseModule, InjectModel, Schema, Prop } from '@nestjs/mongoose';
15
import { DynamicModule } from '@nestjs/common';
16
import { Connection, ConnectOptions, MongooseError } from 'mongoose';
17
```
18
19
For CommonJS:
20
21
```javascript
22
const { MongooseModule, InjectModel, Schema, Prop } = require('@nestjs/mongoose');
23
```
24
25
## Basic Usage
26
27
```typescript
28
import { Module, Injectable } from '@nestjs/common';
29
import { MongooseModule, InjectModel, Schema, Prop, SchemaFactory } from '@nestjs/mongoose';
30
import { Model } from 'mongoose';
31
32
// Define a schema
33
@Schema()
34
export class User {
35
@Prop({ required: true })
36
name: string;
37
38
@Prop()
39
email: string;
40
41
@Prop({ default: Date.now })
42
createdAt: Date;
43
}
44
45
export const UserSchema = SchemaFactory.createForClass(User);
46
47
// Module configuration
48
@Module({
49
imports: [
50
MongooseModule.forRoot('mongodb://localhost/nest'),
51
MongooseModule.forFeature([{ name: User.name, schema: UserSchema }])
52
],
53
providers: [UserService],
54
})
55
export class AppModule {}
56
57
// Service using the model
58
@Injectable()
59
export class UserService {
60
constructor(@InjectModel(User.name) private userModel: Model<User>) {}
61
62
async create(createUserDto: any): Promise<User> {
63
const createdUser = new this.userModel(createUserDto);
64
return createdUser.save();
65
}
66
67
async findAll(): Promise<User[]> {
68
return this.userModel.find().exec();
69
}
70
}
71
```
72
73
## Architecture
74
75
NestJS Mongoose is built around several key components:
76
77
- **Module System**: `MongooseModule` provides configuration for database connections and model registration
78
- **Schema Decorators**: `@Schema()`, `@Prop()`, and `@Virtual()` enable declarative schema definition
79
- **Dependency Injection**: `@InjectModel()` and `@InjectConnection()` integrate with NestJS DI system
80
- **Factory Classes**: `SchemaFactory` and related factories generate Mongoose schemas from decorated classes
81
- **Validation Pipes**: Built-in pipes for MongoDB ObjectId validation and parsing
82
- **Connection Management**: Support for multiple database connections and async configuration
83
84
## Capabilities
85
86
### Module Configuration
87
88
Core module classes for setting up MongoDB connections and registering models in NestJS applications.
89
90
```typescript { .api }
91
class MongooseModule {
92
static forRoot(uri: string, options?: MongooseModuleOptions): DynamicModule;
93
static forRootAsync(options: MongooseModuleAsyncOptions): DynamicModule;
94
static forFeature(models?: ModelDefinition[], connectionName?: string): DynamicModule;
95
static forFeatureAsync(factories?: AsyncModelFactory[], connectionName?: string): DynamicModule;
96
}
97
98
interface MongooseModuleOptions extends ConnectOptions {
99
uri?: string;
100
retryAttempts?: number;
101
retryDelay?: number;
102
connectionName?: string;
103
connectionFactory?: (connection: any, name: string) => any;
104
connectionErrorFactory?: (error: MongooseError) => MongooseError;
105
lazyConnection?: boolean;
106
onConnectionCreate?: (connection: Connection) => void;
107
verboseRetryLog?: boolean;
108
}
109
```
110
111
[Module Configuration](./module-configuration.md)
112
113
### Schema Definition
114
115
Decorators and utilities for defining MongoDB schemas using TypeScript classes with full type safety.
116
117
```typescript { .api }
118
function Schema(options?: SchemaOptions): ClassDecorator;
119
120
function Prop(options?: PropOptions): PropertyDecorator;
121
122
function Virtual(options?: VirtualOptions): PropertyDecorator;
123
```
124
125
[Schema Definition](./schema-definition.md)
126
127
### Dependency Injection
128
129
Decorators for injecting Mongoose models and connections into NestJS services and controllers.
130
131
```typescript { .api }
132
function InjectModel(model: string, connectionName?: string): ParameterDecorator;
133
134
function InjectConnection(name?: string): ParameterDecorator;
135
```
136
137
[Dependency Injection](./dependency-injection.md)
138
139
### Schema Factories
140
141
Factory classes for generating Mongoose schemas and definitions from decorated TypeScript classes.
142
143
```typescript { .api }
144
class SchemaFactory {
145
static createForClass<TClass>(target: Type<TClass>): mongoose.Schema<TClass>;
146
}
147
148
class DefinitionsFactory {
149
static createForClass(target: Type<unknown>): mongoose.SchemaDefinition;
150
}
151
```
152
153
[Schema Factories](./schema-factories.md)
154
155
### Validation Pipes
156
157
Pre-built pipes for validating and parsing MongoDB ObjectIds in request parameters and body data.
158
159
```typescript { .api }
160
class IsObjectIdPipe implements PipeTransform {
161
transform(value: string): string;
162
}
163
164
class ParseObjectIdPipe implements PipeTransform {
165
transform(value: string): Types.ObjectId;
166
}
167
```
168
169
[Validation Pipes](./validation-pipes.md)
170
171
### Utility Functions
172
173
Helper functions for generating dependency injection tokens and handling connection retry logic.
174
175
```typescript { .api }
176
function getModelToken(model: string, connectionName?: string): string;
177
178
function getConnectionToken(name?: string): string;
179
180
function raw(definition: Record<string, any>): Record<string, any>;
181
```
182
183
[Utility Functions](./utility-functions.md)
184
185
## Core Types
186
187
```typescript { .api }
188
interface ModelDefinition {
189
name: string;
190
schema: any;
191
collection?: string;
192
discriminators?: DiscriminatorOptions[];
193
}
194
195
interface AsyncModelFactory {
196
name: string;
197
collection?: string;
198
discriminators?: DiscriminatorOptions[];
199
imports?: any[];
200
useFactory: (...args: any[]) => ModelDefinition['schema'] | Promise<ModelDefinition['schema']>;
201
inject?: any[];
202
}
203
204
interface MongooseModuleAsyncOptions {
205
connectionName?: string;
206
imports?: any[];
207
useExisting?: Type<MongooseOptionsFactory>;
208
useClass?: Type<MongooseOptionsFactory>;
209
useFactory?: (...args: any[]) => Promise<MongooseModuleFactoryOptions> | MongooseModuleFactoryOptions;
210
inject?: any[];
211
}
212
213
type PropOptions = Partial<mongoose.SchemaDefinitionProperty> | mongoose.SchemaType;
214
215
interface VirtualOptions {
216
options?: VirtualTypeOptions;
217
subPath?: string;
218
get?: (...args: any[]) => any;
219
set?: (...args: any[]) => any;
220
}
221
```
222
223
## Constants
224
225
```typescript { .api }
226
const DEFAULT_DB_CONNECTION = 'DatabaseConnection';
227
const MONGOOSE_MODULE_OPTIONS = 'MongooseModuleOptions';
228
const MONGOOSE_CONNECTION_NAME = 'MongooseConnectionName';
229
const RAW_OBJECT_DEFINITION = 'RAW_OBJECT_DEFINITION';
230
```
231
232
## Error Handling
233
234
```typescript { .api }
235
class CannotDetermineTypeError extends Error {
236
constructor(hostClass: string, propertyKey: string);
237
}
238
```