@dqcai/mongodb - Universal MongoDB Adapter for Node.js
π Why Choose @dqcai/mongodb?
@dqcai/mongodb is a revolutionary ORM library that bridges the gap between NoSQL flexibility and SQL familiarity. Built for modern Node.js applications, it transforms your MongoDB operations into an intuitive, type-safe, and highly performant experience.
β¨ Key Features
- ποΈ Schema-Driven Architecture - Define clear database structures with powerful validation
- π SQL-like API - Query NoSQL with familiar syntax that feels like home
- π Full TypeScript Support - Complete type safety from database to application
- π Multi-Document Transactions - ACID compliance when you need it
- π― Intelligent Connection Management - Auto-reconnection and pooling out of the box
- β‘ Performance Optimized - Built for speed with connection pooling and smart caching
- π οΈ Universal DAO Pattern - Consistent CRUD operations across your entire application
- π Advanced Aggregation - Complex queries made simple
- π Full-Text Search - Powerful search capabilities built-in
π Quick Start
Installation
npm install @dqcai/mongodb mongodb
Basic Connection
import { MongoDatabaseFactory } from '@dqcai/mongodb';
const dao = MongoDatabaseFactory.createDAO(
'mongodb://localhost:27017',
'myapp'
);
await dao.connect();
const users = await dao.find('users', { status: 'active' });
console.log(users);
Schema-Powered Development
import { DatabaseSchema } from '@dqcai/mongodb';
const appSchema: DatabaseSchema = {
version: "1.0.0",
database_name: "myapp",
description: "My Application Database",
schemas: {
users: {
description: "User management",
cols: [
{ name: "id", type: "string", primary_key: true },
{ name: "name", type: "string", nullable: false },
{ name: "email", type: "string", unique: true },
{ name: "age", type: "integer" },
{ name: "created_at", type: "timestamp" }
],
indexes: [
{ name: "idx_email", columns: ["email"], unique: true },
{ name: "idx_name", columns: ["name"] }
]
}
}
};
const dao = await MongoDatabaseFactory.createFromSchema(
appSchema,
'mongodb://localhost:27017'
);
π‘ Examples
Modern Service Pattern
import { MongoBaseService } from '@dqcai/mongodb';
interface User {
_id?: string;
name: string;
email: string;
age: number;
created_at?: Date;
}
class UserService extends MongoBaseService<User> {
constructor(dao: MongoUniversalDAO) {
super(dao, 'users');
}
async findByEmail(email: string): Promise<User | null> {
return await this.findOne({ email });
}
async findAdults(): Promise<User[]> {
return await this.findMany({ age: { $gte: 18 } });
}
protected validateDocument(user: Partial<User>) {
const errors: string[] = [];
if (!user.name?.trim()) errors.push('Name is required');
if (!user.email?.includes('@')) errors.push('Valid email required');
if (user.age && (user.age < 0 || user.age > 120)) {
errors.push('Age must be between 0 and 120');
}
return { isValid: errors.length === 0, errors };
}
}
Transaction Support
await userService.executeTransaction(async () => {
const user = await userService.create({
name: 'John Doe',
email: 'john@example.com',
age: 30
});
const postService = new PostService(dao);
await postService.create({
title: 'First Post',
content: 'Hello World!',
user_id: user._id,
published: true
});
});
Advanced Queries & Aggregation
const userStats = await userService.aggregate([
{ $group: { _id: '$age', count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 10 }
]);
const results = await userService.search(
'john',
['name', 'email'],
{ status: 'active' },
{ limit: 20 }
);
const importResult = await userService.bulkInsert(
largeUserArray,
1000
);
ποΈ Architecture & Design Patterns
Universal DAO Pattern
Consistent CRUD operations across all collections with intelligent type inference.
Service Layer Architecture
Build scalable applications with our battle-tested service pattern that encourages separation of concerns.
Schema Migration Support
Seamlessly migrate from traditional MongoDB schemas to our structured approach.
π§ Advanced Configuration
Environment Setup
export const getDatabaseConfig = () => ({
connectionString: process.env.MONGODB_URL || 'mongodb://localhost:27017',
databaseName: process.env.DB_NAME || 'myapp',
options: {
maxPoolSize: parseInt(process.env.DB_POOL_SIZE || '10'),
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
}
});
Logging & Debugging
import { MongoLoggerConfig, MongoModules } from '@dqcai/mongodb';
MongoLoggerConfig.updateConfiguration(
MongoLoggerConfig.createDebugConfig()
);
MongoLoggerConfig.updateConfiguration(
MongoLoggerConfig.createProductionConfig()
);
π Documentation
Core API Methods
connect() | Establish database connection | await dao.connect() |
find(collection, filter, options) | Query documents | await dao.find('users', { age: { $gte: 18 } }) |
insert(collection, doc) | Create new document | await dao.insert('users', userData) |
update(collection, filter, update) | Update documents | await dao.update('users', { _id }, { $set: data }) |
aggregate(collection, pipeline) | Complex queries | await dao.aggregate('users', pipeline) |
Service Layer Methods
create(data) | Create with validation | User registration |
findWithPagination() | Paginated results | List views |
bulkInsert() | Batch operations | Data imports |
executeTransaction() | ACID operations | Complex workflows |
search() | Full-text search | Search functionality |
π― Best Practices
1. Always Define Schemas
Use schemas to ensure data consistency and enable powerful validation.
2. Leverage Indexes
Define indexes in your schema for frequently queried fields.
3. Use Transactions Wisely
Apply transactions for multi-document operations that require consistency.
4. Connection Management
Implement singleton pattern for database connections in production.
5. Error Handling
Implement comprehensive error handling for robust applications.
π Migration Guide
From Traditional MongoDB
await userService.importFromMongo(mongodbRecords, {
batchSize: 500,
transformRecord: (record) => ({
...record,
migrated_at: new Date(),
created_at: new Date(record.created_at)
}),
onProgress: (processed, total) => {
console.log(`Migration progress: ${processed}/${total}`);
}
});
π Performance Tips
- Use connection pooling for production environments
- Implement proper indexing strategies
- Leverage bulk operations for large datasets
- Monitor query performance with built-in logging
- Use aggregation pipelines for complex data processing
π€ Contributing
We welcome contributions from the community! Here's how you can help:
Getting Started
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
Development Setup
git clone https://github.com/cuongdqpayment/dqcai-mongodb.git
cd dqcai-mongodb
npm install
npm test
Contributing Guidelines
- Follow TypeScript best practices
- Write comprehensive tests
- Update documentation for new features
- Maintain backwards compatibility
- Follow semantic versioning
Join our growing community of developers who are building amazing applications with @dqcai/mongodb!
Roadmap
π License
MIT License - see the LICENSE file for details.
@dqcai/mongodb - Where MongoDB meets modern development! β¨
Built with β€οΈ by developers, for developers
β Star us on GitHub β’ π Read the Docs β’ π Get Started