0
# Connection Management
1
2
Database connection establishment, management, and configuration with support for multiple connections, automatic reconnection, and connection pooling.
3
4
## Capabilities
5
6
### Connection Establishment
7
8
Connect to MongoDB databases with comprehensive configuration options and automatic reconnection handling.
9
10
```javascript { .api }
11
/**
12
* Creates a connection to a MongoDB database
13
* @param uri - MongoDB connection string
14
* @param options - Connection configuration options
15
* @returns Promise resolving to mongoose instance
16
*/
17
mongoose.connect(uri: string, options?: ConnectOptions): Promise<typeof mongoose>;
18
19
/**
20
* Creates a new connection instance (for multiple database connections)
21
* @param uri - MongoDB connection string
22
* @param options - Connection configuration options
23
* @returns New connection instance
24
*/
25
mongoose.createConnection(uri: string, options?: ConnectOptions): Connection;
26
27
/**
28
* Closes all connections
29
* @returns Promise that resolves when all connections are closed
30
*/
31
mongoose.disconnect(): Promise<void>;
32
```
33
34
**Usage Examples:**
35
36
```javascript
37
// Basic connection
38
await mongoose.connect('mongodb://localhost:27017/myapp');
39
40
// Connection with options
41
await mongoose.connect('mongodb://localhost:27017/myapp', {
42
maxPoolSize: 10,
43
serverSelectionTimeoutMS: 5000,
44
socketTimeoutMS: 45000,
45
bufferCommands: false,
46
bufferMaxEntries: 0
47
});
48
49
// Multiple connections
50
const conn1 = mongoose.createConnection('mongodb://localhost:27017/app1');
51
const conn2 = mongoose.createConnection('mongodb://localhost:27017/app2');
52
53
// Using connection-specific models
54
const User = conn1.model('User', userSchema);
55
const Product = conn2.model('Product', productSchema);
56
```
57
58
### Connection Object
59
60
The Connection class represents a connection to MongoDB with properties and methods for managing the connection state.
61
62
```javascript { .api }
63
interface Connection extends EventEmitter {
64
/** Current connection state (0=disconnected, 1=connected, 2=connecting, 3=disconnecting) */
65
readyState: number;
66
67
/** Native MongoDB database object */
68
db: mongodb.Db;
69
70
/** Database name */
71
name: string;
72
73
/** Connection host */
74
host: string;
75
76
/** Connection port */
77
port: number;
78
79
/** Models registered on this connection */
80
models: { [key: string]: Model<any> };
81
82
/** Native MongoDB collections */
83
collections: { [key: string]: mongodb.Collection };
84
85
/** Connection configuration */
86
config: any;
87
88
/** Client instance */
89
client: mongodb.MongoClient;
90
91
/** Array of plugins applied to this connection */
92
plugins: Array<any>;
93
94
/** Connection identifier for debugging */
95
id: number;
96
97
/** Username from connection URI */
98
user: string;
99
100
/** Password from connection URI */
101
pass: string;
102
}
103
```
104
105
### Connection Methods
106
107
Methods available on Connection instances for database and collection operations.
108
109
```javascript { .api }
110
interface Connection {
111
/**
112
* Closes the connection
113
* @param force - Force close without waiting for operations to complete
114
* @returns Promise that resolves when connection is closed
115
*/
116
close(force?: boolean): Promise<void>;
117
118
/**
119
* Defines a model on this connection
120
* @param name - Model name
121
* @param schema - Schema definition
122
* @param collection - Collection name (optional)
123
* @returns Model constructor
124
*/
125
model<T>(name: string, schema?: Schema<T>, collection?: string): Model<T>;
126
127
/**
128
* Removes a model from this connection
129
* @param name - Model name to remove
130
* @returns this connection
131
*/
132
deleteModel(name: string): this;
133
134
/**
135
* Gets native collection object
136
* @param name - Collection name
137
* @returns Native MongoDB collection
138
*/
139
collection(name: string): mongodb.Collection;
140
141
/**
142
* Drops the database
143
* @returns Promise that resolves when database is dropped
144
*/
145
dropDatabase(): Promise<void>;
146
147
/**
148
* Drops a specific collection
149
* @param collection - Collection name to drop
150
* @returns Promise that resolves when collection is dropped
151
*/
152
dropCollection(collection: string): Promise<boolean>;
153
154
/**
155
* Synchronizes indexes for all models on this connection
156
* @returns Promise that resolves when indexes are synced
157
*/
158
syncIndexes(): Promise<void>;
159
160
/**
161
* Starts a new session for transactions
162
* @param options - Session options
163
* @returns ClientSession for transaction operations
164
*/
165
startSession(options?: mongodb.SessionOptions): Promise<mongodb.ClientSession>;
166
167
/**
168
* Executes function within a transaction
169
* @param fn - Function to execute in transaction
170
* @param options - Transaction options
171
* @returns Promise with transaction result
172
*/
173
transaction<T>(fn: (session: mongodb.ClientSession) => Promise<T>, options?: any): Promise<T>;
174
175
/**
176
* Creates a change stream on the database
177
* @param pipeline - Aggregation pipeline for filtering changes
178
* @param options - Change stream options
179
* @returns Change stream cursor
180
*/
181
watch(pipeline?: any[], options?: mongodb.ChangeStreamOptions): mongodb.ChangeStream;
182
183
/**
184
* Switch to a different database using the same connection
185
* @param name - Database name
186
* @returns New connection to the specified database
187
*/
188
useDb(name: string): Connection;
189
190
/**
191
* Returns promise that resolves when connection is established
192
* @returns Promise resolving when connected
193
*/
194
asPromise(): Promise<this>;
195
196
/**
197
* Perform cross-collection bulk operations
198
* @returns Bulk operation builder
199
*/
200
bulkWrite<TSchemaMap>(): any;
201
202
/**
203
* Closes and destroys connection permanently
204
* @param force - Force destruction without waiting
205
* @returns Promise that resolves when destroyed
206
*/
207
destroy(force?: boolean): Promise<void>;
208
209
/**
210
* Create collections for all registered models
211
* @param continueOnError - Continue creating collections if one fails
212
* @returns Promise that resolves when collections are created
213
*/
214
createCollections(continueOnError?: boolean): Promise<void>;
215
216
/**
217
* List all collections in the database
218
* @returns Promise with array of collection information
219
*/
220
listCollections(): Promise<CollectionInfo[]>;
221
222
/**
223
* List all databases accessible by this connection
224
* @returns Promise with database list information
225
*/
226
listDatabases(): Promise<ListDatabasesResult>;
227
228
/**
229
* Set MongoDB client instance for this connection
230
* @param client - MongoDB client instance
231
* @returns this connection
232
*/
233
setClient(client: mongodb.MongoClient): this;
234
235
/**
236
* Execute operation within a session context
237
* @param executor - Function to execute with session
238
* @returns Promise with operation result
239
*/
240
withSession<T>(executor: (session: mongodb.ClientSession) => Promise<T>): Promise<T>;
241
}
242
```
243
244
### Connection Events
245
246
Connections emit events for monitoring connection state changes and handling errors.
247
248
```javascript { .api }
249
// Connection events
250
connection.on('connected', () => {}); // Successfully connected
251
connection.on('error', (err) => {}); // Connection error occurred
252
connection.on('disconnected', () => {}); // Connection lost
253
connection.on('reconnected', () => {}); // Successfully reconnected
254
connection.on('close', () => {}); // Connection closed
255
connection.on('fullsetup', () => {}); // All replica set members connected
256
connection.on('all', () => {}); // All replica set members connected
257
connection.on('reconnectFailed', () => {}); // Reconnection failed
258
```
259
260
**Usage Examples:**
261
262
```javascript
263
const connection = mongoose.createConnection('mongodb://localhost:27017/myapp');
264
265
// Handle connection events
266
connection.on('connected', () => {
267
console.log('Connected to MongoDB');
268
});
269
270
connection.on('error', (err) => {
271
console.error('Connection error:', err);
272
});
273
274
connection.on('disconnected', () => {
275
console.log('Disconnected from MongoDB');
276
});
277
278
// Check connection state
279
if (connection.readyState === 1) {
280
console.log('Connection is active');
281
}
282
283
// Use native database operations
284
const db = connection.db;
285
const result = await db.collection('users').findOne({ name: 'John' });
286
```
287
288
### Default Connection
289
290
Mongoose provides a default connection accessible through the main mongoose object.
291
292
```javascript { .api }
293
/** Default connection instance */
294
mongoose.connection: Connection;
295
296
/** Connection state constants */
297
mongoose.STATES: {
298
disconnected: 0;
299
connected: 1;
300
connecting: 2;
301
disconnecting: 3;
302
uninitialized: 99;
303
};
304
```
305
306
**Usage Examples:**
307
308
```javascript
309
// Access default connection
310
const defaultConnection = mongoose.connection;
311
312
// Monitor default connection
313
mongoose.connection.on('connected', () => {
314
console.log('Default connection established');
315
});
316
317
// Check if connected
318
if (mongoose.connection.readyState === mongoose.STATES.connected) {
319
console.log('Ready to perform operations');
320
}
321
```
322
323
## Types
324
325
```javascript { .api }
326
interface ConnectOptions {
327
/** Use new URL parser */
328
useNewUrlParser?: boolean;
329
330
/** Use unified topology */
331
useUnifiedTopology?: boolean;
332
333
/** Buffer commands when not connected */
334
bufferCommands?: boolean;
335
336
/** Max number of buffered commands */
337
bufferMaxEntries?: number;
338
339
/** Auto-create collections */
340
autoCreate?: boolean;
341
342
/** Auto-create indexes */
343
autoIndex?: boolean;
344
345
/** Maximum connection pool size */
346
maxPoolSize?: number;
347
348
/** Minimum connection pool size */
349
minPoolSize?: number;
350
351
/** Max idle time for pooled connections (ms) */
352
maxIdleTimeMS?: number;
353
354
/** Server selection timeout (ms) */
355
serverSelectionTimeoutMS?: number;
356
357
/** Socket timeout (ms) */
358
socketTimeoutMS?: number;
359
360
/** IP family (4 or 6) */
361
family?: number;
362
363
/** Authentication database */
364
authSource?: string;
365
366
/** Username for authentication */
367
user?: string;
368
369
/** Password for authentication */
370
pass?: string;
371
372
/** Database name */
373
dbName?: string;
374
375
/** Write concern */
376
w?: string | number;
377
378
/** Write concern timeout */
379
wtimeout?: number;
380
381
/** Journal write concern */
382
j?: boolean;
383
384
/** Read preference */
385
readPreference?: string;
386
387
/** Read preference tags */
388
readPreferenceTags?: any[];
389
390
/** Replica set name */
391
replicaSet?: string;
392
393
/** SSL options */
394
ssl?: boolean;
395
sslValidate?: boolean;
396
sslCA?: string | string[] | Buffer | Buffer[];
397
sslCert?: string | Buffer;
398
sslKey?: string | Buffer;
399
sslPass?: string;
400
401
/** Additional MongoDB driver options */
402
[key: string]: any;
403
}
404
405
interface CollectionInfo {
406
/** Collection name */
407
name: string;
408
409
/** Collection type */
410
type: string;
411
412
/** Collection options */
413
options: any;
414
415
/** Collection info */
416
info: any;
417
418
/** Collection UUID */
419
idIndex: any;
420
}
421
422
interface ListDatabasesResult {
423
/** Array of database information */
424
databases: Array<{
425
/** Database name */
426
name: string;
427
428
/** Database size in bytes */
429
sizeOnDisk: number;
430
431
/** Whether database is empty */
432
empty: boolean;
433
}>;
434
435
/** Total size of all databases */
436
totalSize: number;
437
}
438
```