0
# Module Configuration
1
2
Core module classes for setting up MongoDB connections and registering models in NestJS applications. The module system provides both synchronous and asynchronous configuration options with support for multiple database connections.
3
4
## Capabilities
5
6
### MongooseModule
7
8
Main module for integrating Mongoose with NestJS applications.
9
10
```typescript { .api }
11
class MongooseModule {
12
/**
13
* Configure the root MongoDB connection
14
* @param uri - MongoDB connection string
15
* @param options - Connection options
16
* @returns DynamicModule for root configuration
17
*/
18
static forRoot(uri: string, options?: MongooseModuleOptions): DynamicModule;
19
20
/**
21
* Configure the root MongoDB connection asynchronously
22
* @param options - Async configuration options
23
* @returns DynamicModule for async root configuration
24
*/
25
static forRootAsync(options: MongooseModuleAsyncOptions): DynamicModule;
26
27
/**
28
* Register models for dependency injection
29
* @param models - Array of model definitions (defaults to empty array)
30
* @param connectionName - Optional connection name for multi-database setup
31
* @returns DynamicModule for feature registration
32
*/
33
static forFeature(models?: ModelDefinition[], connectionName?: string): DynamicModule;
34
35
/**
36
* Register models asynchronously for dependency injection
37
* @param factories - Array of async model factories (defaults to empty array)
38
* @param connectionName - Optional connection name for multi-database setup
39
* @returns DynamicModule for async feature registration
40
*/
41
static forFeatureAsync(factories?: AsyncModelFactory[], connectionName?: string): DynamicModule;
42
}
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
// Basic connection
49
@Module({
50
imports: [
51
MongooseModule.forRoot('mongodb://localhost/nest'),
52
],
53
})
54
export class AppModule {}
55
56
// Connection with options
57
@Module({
58
imports: [
59
MongooseModule.forRoot('mongodb://localhost/nest', {
60
retryAttempts: 5,
61
retryDelay: 1000,
62
connectionName: 'users-db',
63
}),
64
],
65
})
66
export class AppModule {}
67
68
// Async configuration with ConfigService
69
@Module({
70
imports: [
71
MongooseModule.forRootAsync({
72
imports: [ConfigModule],
73
useFactory: async (configService: ConfigService) => ({
74
uri: configService.get<string>('MONGODB_URI'),
75
retryAttempts: 5,
76
}),
77
inject: [ConfigService],
78
}),
79
],
80
})
81
export class AppModule {}
82
83
// Register models
84
@Module({
85
imports: [
86
MongooseModule.forFeature([
87
{ name: User.name, schema: UserSchema },
88
{ name: Product.name, schema: ProductSchema, collection: 'products' }
89
]),
90
],
91
})
92
export class UsersModule {}
93
```
94
95
## Configuration Interfaces
96
97
### MongooseModuleOptions
98
99
Configuration options for Mongoose module connections.
100
101
```typescript { .api }
102
interface MongooseModuleOptions extends ConnectOptions {
103
/** MongoDB connection URI */
104
uri?: string;
105
/** Number of retry attempts for failed connections */
106
retryAttempts?: number;
107
/** Delay between retry attempts in milliseconds */
108
retryDelay?: number;
109
/** Name for this connection (for multiple databases) */
110
connectionName?: string;
111
/** Factory function to customize the connection */
112
connectionFactory?: (connection: any, name: string) => any;
113
/** Factory function to customize connection errors */
114
connectionErrorFactory?: (error: MongooseError) => MongooseError;
115
/** Whether to defer connection until first use */
116
lazyConnection?: boolean;
117
/** Callback when connection is created */
118
onConnectionCreate?: (connection: Connection) => void;
119
/** Enable verbose retry logging */
120
verboseRetryLog?: boolean;
121
}
122
```
123
124
### MongooseModuleAsyncOptions
125
126
Options for asynchronous module configuration.
127
128
```typescript { .api }
129
interface MongooseModuleAsyncOptions {
130
/** Name for this connection (for multiple databases) */
131
connectionName?: string;
132
/** Modules to import for dependencies */
133
imports?: any[];
134
/** Use existing options factory */
135
useExisting?: Type<MongooseOptionsFactory>;
136
/** Use class as options factory */
137
useClass?: Type<MongooseOptionsFactory>;
138
/** Factory function to create options */
139
useFactory?: (...args: any[]) => Promise<MongooseModuleFactoryOptions> | MongooseModuleFactoryOptions;
140
/** Dependencies to inject into factory function */
141
inject?: any[];
142
}
143
```
144
145
### MongooseOptionsFactory
146
147
Factory interface for creating module options.
148
149
```typescript { .api }
150
interface MongooseOptionsFactory {
151
/**
152
* Create Mongoose module options
153
* @returns Options object or promise of options
154
*/
155
createMongooseOptions(): Promise<MongooseModuleOptions> | MongooseModuleOptions;
156
}
157
```
158
159
### MongooseModuleFactoryOptions
160
161
Factory options excluding connection name.
162
163
```typescript { .api }
164
type MongooseModuleFactoryOptions = Omit<MongooseModuleOptions, 'connectionName'>;
165
```
166
167
## Model Registration
168
169
### ModelDefinition
170
171
Interface for defining models to register.
172
173
```typescript { .api }
174
interface ModelDefinition {
175
/** Model name for dependency injection */
176
name: string;
177
/** Mongoose schema for the model */
178
schema: any;
179
/** Optional collection name override */
180
collection?: string;
181
/** Optional discriminator schemas */
182
discriminators?: DiscriminatorOptions[];
183
}
184
```
185
186
### AsyncModelFactory
187
188
Factory interface for asynchronously created models.
189
190
```typescript { .api }
191
interface AsyncModelFactory {
192
/** Model name for dependency injection */
193
name: string;
194
/** Optional collection name override */
195
collection?: string;
196
/** Optional discriminator schemas */
197
discriminators?: DiscriminatorOptions[];
198
/** Modules to import for dependencies */
199
imports?: any[];
200
/** Factory function to create schema */
201
useFactory: (...args: any[]) => ModelDefinition['schema'] | Promise<ModelDefinition['schema']>;
202
/** Dependencies to inject into factory function */
203
inject?: any[];
204
}
205
```
206
207
### DiscriminatorOptions
208
209
Options for discriminator models.
210
211
```typescript { .api }
212
interface DiscriminatorOptions {
213
/** Discriminator name */
214
name: string;
215
/** Discriminator schema */
216
schema: Schema;
217
/** Optional discriminator value */
218
value?: string;
219
}
220
```