mm_mongodb
v1.5.3
Published
MongoDB数据库操作模块,提供简洁易用的API、缓存功能以及完整的Redis兼容接口,支持事件系统、事务和连接池管理
Maintainers
Readme
mm_mongodb
A powerful MongoDB database operation module with Redis-compatible API, connection pooling, and event system support.
Features
- ✅ Complete Redis-compatible API - Use familiar Redis commands with MongoDB
- ✅ Connection Pool Management - Efficient connection pooling with automatic reconnection
- ✅ Transaction Support - Full ACID transactions with session management
- ✅ Event System - Comprehensive event system for monitoring operations
- ✅ Index Management - Easy index creation and management
- ✅ TTL Support - Automatic data expiration with TTL indexes
- ✅ Environment Variable Configuration - Flexible configuration via environment variables
- ✅ Query Injection Protection - Built-in security against NoSQL injection
- ✅ Performance Optimized - Optimized for high-performance database operations
Installation
npm install mm_mongodbQuick Start
Basic Usage
const { MongoDB } = require('mm_mongodb');
// Create MongoDB instance
const db = new MongoDB();
// Connect to database
await db.open();
// Create collection
await db.createTable('users');
// Insert data
await db.insert('users', { name: 'John', age: 25 });
// Query data
const result = await db.get('users', { name: 'John' });
// Update data
await db.set('users', { name: 'John' }, { age: 26 });
// Delete data
await db.del('users', { name: 'John' });
// Close connection
await db.close();Redis-Compatible API
const { mongodb_cache_admin } = require('mm_mongodb');
// Get Redis-compatible cache instance
const cache = mongodb_cache_admin('default');
// Connect to database
await cache.open();
// Use Redis-style commands
await cache.set('name', 'Redis Compatible');
const value = await cache.get('name');
await cache.del('name');
// Hash operations
await cache.hset('user:1', 'name', 'John');
const name = await cache.hget('user:1', 'name');
// List operations
await cache.lpush('messages', 'Hello');
await cache.rpush('messages', 'World');
const messages = await cache.lrange('messages', 0, -1);
// Set operations
await cache.sadd('users:online', 'user1', 'user2');
const members = await cache.smembers('users:online');Configuration
Environment Variables
Configure MongoDB connection via environment variables:
MONGO_URL=mongodb://username:password@host:port/database
MONGO_HOST=localhost
MONGO_PORT=27017
MONGO_USERNAME=username
MONGO_PASSWORD=password
MONGO_DATABASE=database
MONGO_AUTH_SOURCE=adminConfiguration File
Create config.tpl.json in your project root:
{
"mongodb": {
"url": "mongodb://username:password@host:port/database",
"poolSize": 20,
"minPoolSize": 5,
"maxPoolSize": 100,
"waitQueueTimeoutMS": 10000,
"connectTimeoutMS": 10000,
"socketTimeoutMS": 45000,
"authSource": "admin",
"authMechanism": "DEFAULT"
}
}API Documentation
Core MongoDB Class
Constructor
new MongoDB(scope = 'default', dir = '', config = {})Connection Management
open()- Connect to databaseclose()- Close database connectionsetUrl(url)- Set connection URLsetConfig(config)- Set configuration
Collection Operations
createTable(tableName)- Create collectiondropTable(tableName)- Drop collectionexistsTable(tableName)- Check if collection exists
Data Operations
insert(tableName, data)- Insert documentinsertBatch(tableName, datas)- Batch insert documentsget(tableName, query, options)- Query documentsgetOne(tableName, query, options)- Query single documentset(tableName, query, data, options)- Update documentsdel(tableName, query, options)- Delete documentscount(tableName, query)- Count documents
Transaction Support
startTransaction()- Start transactioncommitTransaction(session)- Commit transactionrollbackTransaction(session)- Rollback transaction
Index Management
createIndex(tableName, keys, options)- Create indexcreateTTLIndex(tableName, keys, expireAfterSeconds)- Create TTL indexgetIndexes(tableName)- Get index informationdropIndex(tableName, indexName)- Drop index
Redis-Compatible API
Key-Value Operations
set(key, value, seconds)- Set key with optional expirationget(key)- Get value by keydel(key)- Delete keyhas(key)/exists(key)- Check if key existsclear(prefix)- Clear keys with optional prefixkeys(pattern)- Get matching keysttl(key)- Get time to liveexpire(key, seconds)- Set expiration timeadd(key, value)- Add key if not exists
Hash Operations
hset(key, field, value)- Set hash fieldhget(key, field)- Get hash fieldhgetall(key)- Get all hash fieldshmset(key, object)- Set multiple hash fieldshmget(key, ...fields)- Get multiple hash fieldshdel(key, field)- Delete hash fieldhdelMulti(key, ...fields)- Delete multiple hash fieldshexists(key, field)- Check if hash field existshkeys(key)- Get all hash field nameshvals(key)- Get all hash field valueshlen(key)- Get number of hash fields
List Operations
lpush(key, value)- Push to left of listrpush(key, value)- Push to right of listlrange(key, start, stop)- Get list rangelindex(key, index)- Get list element by indexllen(key)- Get list lengthlpop(key)- Pop from left of listrpop(key)- Pop from right of listlset(key, index, value)- Set list element by indexlrem(key, count, value)- Remove list elementsltrim(key, start, stop)- Trim list
Set Operations
sadd(key, ...members)- Add set memberssaddMulti(key, ...members)- Add multiple set memberssrem(key, member)- Remove set membersremMulti(key, ...members)- Remove multiple set memberssmembers(key)- Get all set membersscard(key)- Get set sizesismember(key, member)- Check if member exists in setsdiff(key1, key2)- Get set differencesinter(key1, key2)- Get set intersectionsunion(key1, key2)- Get set union
Sorted Set Operations
zadd(key, member, score)- Add sorted set memberzrem(key, member)- Remove sorted set memberzrangebyscore(key, min, max)- Get members by score rangezscore(key, member)- Get member scorezcard(key)- Get sorted set size
Batch Operations
mset(object)- Set multiple keysmget(...keys)- Get multiple keysdel(...keys)- Delete multiple keys
Numeric Operations
incr(key)- Increment by 1decr(key)- Decrement by 1addInt(key, value)- Add integer valueaddFloat(key, value)- Add float valueaddStr(key, value)- Append string
Event System
mm_mongodb provides a comprehensive event system for monitoring database operations:
const db = new MongoDB();
await db.open();
// Listen to operation events
db.on('set_before', (data) => {
console.log('Before set operation:', data);
});
db.on('set_after', (data) => {
console.log('After set operation:', data);
});
db.on('set_error', (data) => {
console.error('Set operation error:', data);
});
// Trigger events
await db.set('test_key', 'test_value');Supported Events
{action}_before- Before operation execution{action}_after- After operation completion{action}_error- On operation error
Where {action} can be: set, del, add, hset, lpush, sadd, zadd, etc.
Performance Optimization
- Use Connection Pooling - Always use
mongodb_adminormongodb_cache_adminfor connection pooling - Create Appropriate Indexes - Index frequently queried fields
- Use Batch Operations - Prefer
mset,mget,insertBatchfor multiple operations - Set Expiration Times - Use TTL indexes for temporary data
- Optimize Queries - Avoid full collection scans, use precise queries
Migration from Redis
Migrating from Redis to mm_mongodb is straightforward:
// Redis client (original)
// const redis = require('redis');
// const client = redis.createClient();
// await client.connect();
// mm_mongodb (replacement)
const { mongodb_cache_admin } = require('mm_mongodb');
const cache = mongodb_cache_admin('default');
await cache.open();
// Your Redis commands remain the same
await cache.set('key', 'value');
const value = await cache.get('key');Security Considerations
- Passwords are automatically URI-encoded for secure transmission
- Built-in query injection protection
- Environment variables for sensitive configuration
- Automatic connection retry for improved stability
- Avoid using raw user input in queries
Dependencies
Compatibility
- Node.js: >= 14.0.0 (Recommended: 16.0.0+)
- MongoDB: 4.0+
Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/your-feature - Commit your changes:
git commit -m "feat: add your feature" - Push to the branch:
git push origin feature/your-feature - Submit a pull request
Issues and Support
If you encounter any issues or have questions:
- GitHub Issues: https://github.com/qwwang/mm_mongodb/issues
- NPM Package: https://www.npmjs.com/package/mm_mongodb
License
This project is licensed under the MIT License - see the LICENSE file for details.
Author
Qiu Wenwu - qww.elins.cn
Acknowledgments
Thanks to all contributors and users who have helped improve mm_mongodb!
