0
# Utilities and Helpers
1
2
Helper functions for common MongoDB operations including ObjectID conversion and validation.
3
4
## Capabilities
5
6
### ObjectID Utilities
7
8
Helper functions for working with MongoDB ObjectIDs.
9
10
```javascript { .api }
11
/**
12
* Convert string to ObjectID
13
* @param {string|ObjectID|number} hex - Input to convert
14
* @returns {ObjectID|*} ObjectID if valid hex string, otherwise original input
15
*/
16
helper.toObjectID(hex);
17
18
/**
19
* Check if string is valid ObjectID format
20
* @param {string} idstr - String to validate
21
* @returns {boolean} true if valid ObjectID format
22
*/
23
helper.isObjectID(idstr);
24
```
25
26
**Usage Examples:**
27
28
```javascript
29
const mongoskin = require('mongoskin');
30
31
// Convert string to ObjectID
32
const stringId = '507f1f77bcf86cd799439011';
33
const objectId = mongoskin.helper.toObjectID(stringId);
34
console.log('ObjectID:', objectId);
35
36
// Already ObjectID - returns as-is
37
const existingId = new mongoskin.ObjectID();
38
const sameId = mongoskin.helper.toObjectID(existingId);
39
console.log('Same ObjectID:', sameId === existingId); // true
40
41
// Invalid string - returns original
42
const invalidId = 'not-an-id';
43
const result = mongoskin.helper.toObjectID(invalidId);
44
console.log('Invalid ID returned as-is:', result === invalidId); // true
45
46
// Validate ObjectID format
47
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('507f1f77bcf86cd799439011')); // true
48
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('invalid-id')); // false
49
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('507f1f77bcf86cd799439011123')); // false (too long)
50
```
51
52
### Skin Class Factory
53
54
Core utility for creating wrapper classes with lazy connection pattern.
55
56
```javascript { .api }
57
/**
58
* Create a Skin wrapper class for MongoDB native class
59
* @param {Function} NativeClass - MongoDB native class constructor
60
* @param {boolean} [useNativeConstructor] - Whether to use native constructor
61
* @returns {Function} Skin class constructor
62
*/
63
utils.makeSkinClass(NativeClass, useNativeConstructor);
64
```
65
66
**Usage Examples:**
67
68
```javascript
69
const mongoskin = require('mongoskin');
70
const mongodb = require('mongodb');
71
72
// Create custom Skin class wrapper
73
const CustomCollection = mongoskin.utils.makeSkinClass(mongodb.Collection);
74
75
// The created class will have:
76
// - Lazy connection pattern
77
// - All native methods proxied
78
// - State management (CLOSE, OPENING, OPEN)
79
// - Event-driven connection lifecycle
80
81
console.log('Custom class name:', CustomCollection._class_name); // 'SkinCollection'
82
83
// Example of extending the custom class
84
CustomCollection.prototype.findActiveUsers = function(callback) {
85
return this.findItems({ active: true }, callback);
86
};
87
88
// Use the custom class
89
const customCollection = new CustomCollection();
90
// customCollection now has lazy connection and all Collection methods
91
```
92
93
### Connection State Constants
94
95
Constants for managing connection states in Skin classes.
96
97
```javascript { .api }
98
/** Connection is closed */
99
const STATE_CLOSE = 0;
100
101
/** Connection is opening */
102
const STATE_OPENING = 1;
103
104
/** Connection is open and ready */
105
const STATE_OPEN = 2;
106
107
/** Default MongoDB port */
108
const DEFAULT_PORT = 27017;
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
const mongoskin = require('mongoskin');
115
116
// Access state constants
117
console.log('Close state:', mongoskin.STATE_CLOSE); // 0
118
console.log('Opening state:', mongoskin.STATE_OPENING); // 1
119
console.log('Open state:', mongoskin.STATE_OPEN); // 2
120
console.log('Default port:', mongoskin.DEFAULT_PORT); // 27017
121
122
// Check connection state
123
const db = mongoskin.db('mongodb://localhost:27017/myapp');
124
console.log('Initial state:', db._state === mongoskin.STATE_CLOSE); // true
125
126
db.open((err, database) => {
127
if (err) throw err;
128
console.log('Open state:', db._state === mongoskin.STATE_OPEN); // true
129
});
130
```
131
132
### MongoDB Native Types
133
134
Direct access to MongoDB native types and classes.
135
136
```javascript { .api }
137
// Core MongoDB types (re-exported from mongodb module)
138
class ObjectID {
139
constructor(id?: string | Buffer | number): ObjectID;
140
toString(): string;
141
toHexString(): string;
142
equals(otherID: ObjectID): boolean;
143
getTimestamp(): Date;
144
static createFromHexString(hex: string): ObjectID;
145
static createFromTime(time: number): ObjectID;
146
static isValid(id: string | ObjectID | number): boolean;
147
}
148
149
class Long {
150
constructor(low: number, high: number, unsigned?: boolean): Long;
151
toString(radix?: number): string;
152
toNumber(): number;
153
equals(other: Long): boolean;
154
static fromNumber(value: number): Long;
155
static fromString(str: string, radix?: number): Long;
156
}
157
158
class Binary {
159
constructor(buffer: Buffer, subType?: number): Binary;
160
toString(format?: string): string;
161
length(): number;
162
}
163
164
class Code {
165
constructor(code: string, scope?: object): Code;
166
toString(): string;
167
}
168
169
class Timestamp {
170
constructor(low: number, high: number): Timestamp;
171
toString(): string;
172
equals(other: Timestamp): boolean;
173
}
174
```
175
176
**Usage Examples:**
177
178
```javascript
179
const mongoskin = require('mongoskin');
180
181
// Create ObjectID
182
const objectId = new mongoskin.ObjectID();
183
console.log('New ObjectID:', objectId.toString());
184
185
// Create ObjectID from hex string
186
const fromHex = mongoskin.ObjectID.createFromHexString('507f1f77bcf86cd799439011');
187
console.log('From hex:', fromHex);
188
189
// Check if ObjectID is valid
190
console.log('Valid?', mongoskin.ObjectID.isValid('507f1f77bcf86cd799439011')); // true
191
192
// Create Long number
193
const longNum = mongoskin.Long.fromNumber(12345678901234);
194
console.log('Long number:', longNum.toString());
195
196
// Create Binary data
197
const binaryData = new mongoskin.Binary(Buffer.from('Hello World'));
198
console.log('Binary length:', binaryData.length());
199
200
// Create Code object
201
const jsCode = new mongoskin.Code('function() { return this.name; }');
202
console.log('Code:', jsCode.toString());
203
204
// Create Timestamp
205
const timestamp = new mongoskin.Timestamp(0, Math.floor(Date.now() / 1000));
206
console.log('Timestamp:', timestamp.toString());
207
```
208
209
### Connection Utilities
210
211
Utilities for connection string parsing and management.
212
213
```javascript { .api }
214
/**
215
* Parse MongoDB connection string
216
* @param {string} connectionString - MongoDB URI
217
* @returns {object} Parsed connection components
218
*/
219
parseConnectionString(connectionString);
220
221
/**
222
* Build connection string from components
223
* @param {object} components - Connection components
224
* @returns {string} MongoDB connection URI
225
*/
226
buildConnectionString(components);
227
```
228
229
**Usage Examples:**
230
231
```javascript
232
const mongoskin = require('mongoskin');
233
234
// Parse connection string (if available)
235
const parsed = {
236
protocol: 'mongodb',
237
hosts: [{ host: 'localhost', port: 27017 }],
238
database: 'myapp',
239
auth: { username: 'user', password: 'pass' },
240
options: { authSource: 'admin' }
241
};
242
243
// Common connection patterns
244
const connections = {
245
local: 'mongodb://localhost:27017/myapp',
246
authenticated: 'mongodb://user:pass@localhost:27017/myapp',
247
replicaSet: 'mongodb://host1:27017,host2:27017/myapp?replicaSet=rs0',
248
withOptions: 'mongodb://localhost:27017/myapp?authSource=admin&ssl=true'
249
};
250
251
console.log('Connection examples:', connections);
252
```
253
254
### Error Handling Utilities
255
256
Utilities for handling MongoDB errors and exceptions.
257
258
```javascript { .api }
259
/**
260
* Check if error is a connection error
261
* @param {Error} error - Error object
262
* @returns {boolean} true if connection error
263
*/
264
isConnectionError(error);
265
266
/**
267
* Check if error is a duplicate key error
268
* @param {Error} error - Error object
269
* @returns {boolean} true if duplicate key error
270
*/
271
isDuplicateKeyError(error);
272
273
/**
274
* Get error code from MongoDB error
275
* @param {Error} error - Error object
276
* @returns {number} Error code
277
*/
278
getErrorCode(error);
279
```
280
281
**Usage Examples:**
282
283
```javascript
284
const mongoskin = require('mongoskin');
285
const db = mongoskin.db('mongodb://localhost:27017/myapp');
286
287
// Error handling in operations
288
db.collection('users').insert({ email: 'test@example.com' }, (err, result) => {
289
if (err) {
290
// Check error type (pseudo-code - actual implementation may vary)
291
if (err.code === 11000) {
292
console.log('Duplicate key error - email already exists');
293
} else if (err.name === 'MongoNetworkError') {
294
console.log('Connection error - retrying...');
295
} else {
296
console.log('Other error:', err.message);
297
}
298
return;
299
}
300
301
console.log('User inserted successfully');
302
});
303
304
// Connection error handling
305
db.open((err, database) => {
306
if (err) {
307
console.log('Failed to connect:', err.message);
308
309
// Check specific error conditions
310
if (err.name === 'MongoAuthenticationError') {
311
console.log('Authentication failed - check credentials');
312
} else if (err.name === 'MongoNetworkError') {
313
console.log('Network error - check server connectivity');
314
}
315
316
return;
317
}
318
319
console.log('Connected successfully');
320
});
321
```
322
323
### Performance Utilities
324
325
Utilities for monitoring and optimizing performance.
326
327
```javascript { .api }
328
/**
329
* Create connection pool with specific size
330
* @param {string} connectionString - MongoDB URI
331
* @param {number} poolSize - Pool size
332
* @returns {SkinDb} Database with connection pool
333
*/
334
createPool(connectionString, poolSize);
335
336
/**
337
* Get connection pool statistics
338
* @param {SkinDb} db - Database instance
339
* @returns {object} Pool statistics
340
*/
341
getPoolStats(db);
342
```
343
344
**Usage Examples:**
345
346
```javascript
347
const mongoskin = require('mongoskin');
348
349
// Connection with specific pool size
350
const db = mongoskin.db('mongodb://localhost:27017/myapp', {
351
poolSize: 10,
352
bufferMaxEntries: 0,
353
useNewUrlParser: true,
354
useUnifiedTopology: true
355
});
356
357
// Monitor connection usage
358
db.open((err, database) => {
359
if (err) throw err;
360
361
console.log('Connection pool ready');
362
363
// Perform multiple operations to test pool
364
for (let i = 0; i < 20; i++) {
365
db.collection('test').findOne({}, (err, doc) => {
366
if (err) console.log('Query error:', err);
367
else console.log('Query', i, 'completed');
368
});
369
}
370
});
371
```