mongodb-client-helper
v1.0.1
Published
A modern MongoDB client helper with TypeScript support, auto-reconnection, and simplified operations for Node.js 18+
Maintainers
Readme
mongodb-client-helper
Synopsis
A modern MongoDB client helper that adds enhanced features to the native MongoDB driver including auto-reconnection, simplified operations, TypeScript support, and developer-friendly APIs.
Features
- 🚀 Modern: Built for Node.js 18+ with MongoDB 6.x driver
- 📝 TypeScript: Full TypeScript support with comprehensive type definitions
- 🔄 Auto-reconnection: Automatic reconnection with configurable retry limits
- 🛠️ Developer-friendly: Simplified API for common MongoDB operations
- ⚡ Performance: Optimized connection pooling and timeout handling
- 🔒 Secure: Built-in validation and error handling
Requirements
- Node.js >= 18.0.0
- MongoDB Server >= 4.4
- TypeScript >= 5.0 (for TypeScript projects)
Installation
npm install mongodb-client-helperQuick Start
JavaScript (CommonJS)
const mongoDbHelper = require('mongodb-client-helper');
const client = mongoDbHelper();TypeScript / ES6 Modules
import mongoDbHelper from 'mongodb-client-helper';
const client = mongoDbHelper();API Reference
Connection
client.connect(config)
Establishes a connection to MongoDB with auto-reconnection support.
const config = {
host: "localhost",
port: 27017,
user: "username",
password: "password",
dbName: "myDatabase",
authSource: "admin",
// Optional settings
forceReconnect: true,
forceReconnectLimit: 5,
replicaSet: "myReplicaSet",
maxPoolSize: 20,
serverSelectionTimeoutMS: 5000
};
try {
await client.connect(config);
console.log('Connected to MongoDB');
} catch (error) {
console.error('Connection failed:', error);
}CRUD Operations
client.find(collection, filter, projection, sort, limit)
// Find documents with optional parameters
const results = await client.find(
'users',
{ status: 'active' }, // filter
{ name: 1, email: 1 }, // projection
{ createdAt: -1 }, // sort
10 // limit
);client.insert(collection, documents)
// Insert single document
await client.insert('users', { name: 'John', email: '[email protected]' });
// Insert multiple documents
await client.insert('users', [
{ name: 'Alice', email: '[email protected]' },
{ name: 'Bob', email: '[email protected]' }
]);client.update(collection, filter, values, upsert)
// Update documents
await client.update(
'users',
{ _id: userId },
{ $set: { lastLogin: new Date() } },
false // upsert
);client.delete(collection, filter)
// Delete documents
await client.delete('users', { status: 'inactive' });Advanced Operations
client.aggregate(collection, pipeline)
// Aggregation pipeline
const results = await client.aggregate('orders', [
{ $match: { status: 'completed' } },
{ $group: { _id: '$customerId', total: { $sum: '$amount' } } },
{ $sort: { total: -1 } }
]);client.replace(collection, filter, replacement)
// Replace entire document
await client.replace('users', { _id: userId }, {
name: 'Updated Name',
email: '[email protected]',
modifiedAt: new Date()
});client.count(collection, filter)
// Count documents
const userCount = await client.count('users', { status: 'active' });Utility Methods
client.eval(script, inputs) ⚠️
Warning: Use with caution in production environments.
// Execute custom script (advanced users only)
const inputs = { database: "mydb", collection: "users" };
const script = "db.db(inputs.database).collection(inputs.collection).find({}).toArray()";
const result = await client.eval(script, inputs);client.close()
// Close connection
await client.close();Native MongoDB Exports
Access native MongoDB driver components:
const client = mongoDbHelper();
// Native MongoDB classes
const { ObjectId, MongoClient, Binary, Decimal128 } = client;
// Create ObjectId
const id = new ObjectId();
// Access other native components
const {
MongoError,
GridFSBucket,
ReadPreference,
Timestamp,
// ... and more
} = client;Complete Example
import mongoDbHelper from 'mongodb-client-helper';
async function example() {
const client = mongoDbHelper();
try {
// Connect
await client.connect({
host: 'localhost',
port: 27017,
user: 'username',
password: 'password',
dbName: 'myapp'
});
// Insert data
await client.insert('users', {
name: 'John Doe',
email: '[email protected]',
createdAt: new Date()
});
// Find data
const users = await client.find('users', { name: 'John Doe' });
console.log('Found users:', users);
// Update data
await client.update('users',
{ name: 'John Doe' },
{ $set: { lastLogin: new Date() } }
);
// Close connection
await client.close();
} catch (error) {
console.error('Error:', error);
}
}
example();TypeScript Support
Full TypeScript definitions included:
import mongoDbHelper, { MongoConfig } from 'mongodb-client-helper';
const client = mongoDbHelper();
const config: MongoConfig = {
host: 'localhost',
port: 27017,
dbName: 'myapp'
};
await client.connect(config);License
ISC - See LICENSE file for details.
Contributing
Contributions welcome! Please read our contributing guidelines and submit pull requests to our repository.
