npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

mongodb-client-helper

v1.0.1

Published

A modern MongoDB client helper with TypeScript support, auto-reconnection, and simplified operations for Node.js 18+

Readme

mongodb-client-helper

npm version License: ISC Node.js Version

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-helper

Quick 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.

Support