A simplified wrapper layer above the node-mongodb-native driver that provides a streamlined API for MongoDB database operations
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Helper functions for common MongoDB operations including ObjectID conversion and validation.
Helper functions for working with MongoDB ObjectIDs.
/**
* Convert string to ObjectID
* @param {string|ObjectID|number} hex - Input to convert
* @returns {ObjectID|*} ObjectID if valid hex string, otherwise original input
*/
helper.toObjectID(hex);
/**
* Check if string is valid ObjectID format
* @param {string} idstr - String to validate
* @returns {boolean} true if valid ObjectID format
*/
helper.isObjectID(idstr);Usage Examples:
const mongoskin = require('mongoskin');
// Convert string to ObjectID
const stringId = '507f1f77bcf86cd799439011';
const objectId = mongoskin.helper.toObjectID(stringId);
console.log('ObjectID:', objectId);
// Already ObjectID - returns as-is
const existingId = new mongoskin.ObjectID();
const sameId = mongoskin.helper.toObjectID(existingId);
console.log('Same ObjectID:', sameId === existingId); // true
// Invalid string - returns original
const invalidId = 'not-an-id';
const result = mongoskin.helper.toObjectID(invalidId);
console.log('Invalid ID returned as-is:', result === invalidId); // true
// Validate ObjectID format
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('507f1f77bcf86cd799439011')); // true
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('invalid-id')); // false
console.log('Valid ObjectID?', mongoskin.helper.isObjectID('507f1f77bcf86cd799439011123')); // false (too long)Core utility for creating wrapper classes with lazy connection pattern.
/**
* Create a Skin wrapper class for MongoDB native class
* @param {Function} NativeClass - MongoDB native class constructor
* @param {boolean} [useNativeConstructor] - Whether to use native constructor
* @returns {Function} Skin class constructor
*/
utils.makeSkinClass(NativeClass, useNativeConstructor);Usage Examples:
const mongoskin = require('mongoskin');
const mongodb = require('mongodb');
// Create custom Skin class wrapper
const CustomCollection = mongoskin.utils.makeSkinClass(mongodb.Collection);
// The created class will have:
// - Lazy connection pattern
// - All native methods proxied
// - State management (CLOSE, OPENING, OPEN)
// - Event-driven connection lifecycle
console.log('Custom class name:', CustomCollection._class_name); // 'SkinCollection'
// Example of extending the custom class
CustomCollection.prototype.findActiveUsers = function(callback) {
return this.findItems({ active: true }, callback);
};
// Use the custom class
const customCollection = new CustomCollection();
// customCollection now has lazy connection and all Collection methodsConstants for managing connection states in Skin classes.
/** Connection is closed */
const STATE_CLOSE = 0;
/** Connection is opening */
const STATE_OPENING = 1;
/** Connection is open and ready */
const STATE_OPEN = 2;
/** Default MongoDB port */
const DEFAULT_PORT = 27017;Usage Examples:
const mongoskin = require('mongoskin');
// Access state constants
console.log('Close state:', mongoskin.STATE_CLOSE); // 0
console.log('Opening state:', mongoskin.STATE_OPENING); // 1
console.log('Open state:', mongoskin.STATE_OPEN); // 2
console.log('Default port:', mongoskin.DEFAULT_PORT); // 27017
// Check connection state
const db = mongoskin.db('mongodb://localhost:27017/myapp');
console.log('Initial state:', db._state === mongoskin.STATE_CLOSE); // true
db.open((err, database) => {
if (err) throw err;
console.log('Open state:', db._state === mongoskin.STATE_OPEN); // true
});Direct access to MongoDB native types and classes.
// Core MongoDB types (re-exported from mongodb module)
class ObjectID {
constructor(id?: string | Buffer | number): ObjectID;
toString(): string;
toHexString(): string;
equals(otherID: ObjectID): boolean;
getTimestamp(): Date;
static createFromHexString(hex: string): ObjectID;
static createFromTime(time: number): ObjectID;
static isValid(id: string | ObjectID | number): boolean;
}
class Long {
constructor(low: number, high: number, unsigned?: boolean): Long;
toString(radix?: number): string;
toNumber(): number;
equals(other: Long): boolean;
static fromNumber(value: number): Long;
static fromString(str: string, radix?: number): Long;
}
class Binary {
constructor(buffer: Buffer, subType?: number): Binary;
toString(format?: string): string;
length(): number;
}
class Code {
constructor(code: string, scope?: object): Code;
toString(): string;
}
class Timestamp {
constructor(low: number, high: number): Timestamp;
toString(): string;
equals(other: Timestamp): boolean;
}Usage Examples:
const mongoskin = require('mongoskin');
// Create ObjectID
const objectId = new mongoskin.ObjectID();
console.log('New ObjectID:', objectId.toString());
// Create ObjectID from hex string
const fromHex = mongoskin.ObjectID.createFromHexString('507f1f77bcf86cd799439011');
console.log('From hex:', fromHex);
// Check if ObjectID is valid
console.log('Valid?', mongoskin.ObjectID.isValid('507f1f77bcf86cd799439011')); // true
// Create Long number
const longNum = mongoskin.Long.fromNumber(12345678901234);
console.log('Long number:', longNum.toString());
// Create Binary data
const binaryData = new mongoskin.Binary(Buffer.from('Hello World'));
console.log('Binary length:', binaryData.length());
// Create Code object
const jsCode = new mongoskin.Code('function() { return this.name; }');
console.log('Code:', jsCode.toString());
// Create Timestamp
const timestamp = new mongoskin.Timestamp(0, Math.floor(Date.now() / 1000));
console.log('Timestamp:', timestamp.toString());Utilities for connection string parsing and management.
/**
* Parse MongoDB connection string
* @param {string} connectionString - MongoDB URI
* @returns {object} Parsed connection components
*/
parseConnectionString(connectionString);
/**
* Build connection string from components
* @param {object} components - Connection components
* @returns {string} MongoDB connection URI
*/
buildConnectionString(components);Usage Examples:
const mongoskin = require('mongoskin');
// Parse connection string (if available)
const parsed = {
protocol: 'mongodb',
hosts: [{ host: 'localhost', port: 27017 }],
database: 'myapp',
auth: { username: 'user', password: 'pass' },
options: { authSource: 'admin' }
};
// Common connection patterns
const connections = {
local: 'mongodb://localhost:27017/myapp',
authenticated: 'mongodb://user:pass@localhost:27017/myapp',
replicaSet: 'mongodb://host1:27017,host2:27017/myapp?replicaSet=rs0',
withOptions: 'mongodb://localhost:27017/myapp?authSource=admin&ssl=true'
};
console.log('Connection examples:', connections);Utilities for handling MongoDB errors and exceptions.
/**
* Check if error is a connection error
* @param {Error} error - Error object
* @returns {boolean} true if connection error
*/
isConnectionError(error);
/**
* Check if error is a duplicate key error
* @param {Error} error - Error object
* @returns {boolean} true if duplicate key error
*/
isDuplicateKeyError(error);
/**
* Get error code from MongoDB error
* @param {Error} error - Error object
* @returns {number} Error code
*/
getErrorCode(error);Usage Examples:
const mongoskin = require('mongoskin');
const db = mongoskin.db('mongodb://localhost:27017/myapp');
// Error handling in operations
db.collection('users').insert({ email: 'test@example.com' }, (err, result) => {
if (err) {
// Check error type (pseudo-code - actual implementation may vary)
if (err.code === 11000) {
console.log('Duplicate key error - email already exists');
} else if (err.name === 'MongoNetworkError') {
console.log('Connection error - retrying...');
} else {
console.log('Other error:', err.message);
}
return;
}
console.log('User inserted successfully');
});
// Connection error handling
db.open((err, database) => {
if (err) {
console.log('Failed to connect:', err.message);
// Check specific error conditions
if (err.name === 'MongoAuthenticationError') {
console.log('Authentication failed - check credentials');
} else if (err.name === 'MongoNetworkError') {
console.log('Network error - check server connectivity');
}
return;
}
console.log('Connected successfully');
});Utilities for monitoring and optimizing performance.
/**
* Create connection pool with specific size
* @param {string} connectionString - MongoDB URI
* @param {number} poolSize - Pool size
* @returns {SkinDb} Database with connection pool
*/
createPool(connectionString, poolSize);
/**
* Get connection pool statistics
* @param {SkinDb} db - Database instance
* @returns {object} Pool statistics
*/
getPoolStats(db);Usage Examples:
const mongoskin = require('mongoskin');
// Connection with specific pool size
const db = mongoskin.db('mongodb://localhost:27017/myapp', {
poolSize: 10,
bufferMaxEntries: 0,
useNewUrlParser: true,
useUnifiedTopology: true
});
// Monitor connection usage
db.open((err, database) => {
if (err) throw err;
console.log('Connection pool ready');
// Perform multiple operations to test pool
for (let i = 0; i < 20; i++) {
db.collection('test').findOne({}, (err, doc) => {
if (err) console.log('Query error:', err);
else console.log('Query', i, 'completed');
});
}
});