
Product
Introducing Webhook Events for Alert Changes
Add real-time Socket webhook events to your workflows to automatically receive software supply chain alert changes in real time.
@dqcai/mongodb
Advanced tools
Transform MongoDB into a SQL-like experience with modern ORM capabilities
📖 Documentation • 🚀 Quick Start • 💡 Examples • 🤝 Contributing
@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.
npm install @dqcai/mongodb mongodb
import { MongoDatabaseFactory } from '@dqcai/mongodb';
// Create DAO instance
const dao = MongoDatabaseFactory.createDAO(
'mongodb://localhost:27017',
'myapp'
);
// Connect and start using
await dao.connect();
const users = await dao.find('users', { status: 'active' });
console.log(users);
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"] }
]
}
}
};
// Create DAO from schema
const dao = await MongoDatabaseFactory.createFromSchema(
appSchema,
'mongodb://localhost:27017'
);
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 };
}
}
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
});
// Both operations succeed or fail together
});
// Complex aggregation made simple
const userStats = await userService.aggregate([
{ $group: { _id: '$age', count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 10 }
]);
// Full-text search
const results = await userService.search(
'john',
['name', 'email'],
{ status: 'active' },
{ limit: 20 }
);
// Bulk operations
const importResult = await userService.bulkInsert(
largeUserArray,
1000 // batch size
);
Consistent CRUD operations across all collections with intelligent type inference.
Build scalable applications with our battle-tested service pattern that encourages separation of concerns.
Seamlessly migrate from traditional MongoDB schemas to our structured approach.
// config/database.ts
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,
}
});
import { MongoLoggerConfig, MongoModules } from '@dqcai/mongodb';
// Development mode
MongoLoggerConfig.updateConfiguration(
MongoLoggerConfig.createDebugConfig()
);
// Production mode
MongoLoggerConfig.updateConfiguration(
MongoLoggerConfig.createProductionConfig()
);
| Method | Description | Example |
|---|---|---|
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) |
| Method | Description | Use Case |
|---|---|---|
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 |
Use schemas to ensure data consistency and enable powerful validation.
Define indexes in your schema for frequently queried fields.
Apply transactions for multi-document operations that require consistency.
Implement singleton pattern for database connections in production.
Implement comprehensive error handling for robust applications.
// Import existing MongoDB data
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}`);
}
});
We welcome contributions from the community! Here's how you can help:
git clone https://github.com/cuongdqpayment/dqcai-mongodb.git
cd dqcai-mongodb
npm install
npm test
Join our growing community of developers who are building amazing applications with @dqcai/mongodb!
MIT License - see the LICENSE file for details.
@dqcai/mongodb - Where MongoDB meets modern development! ✨
Built with ❤️ by developers, for developers
FAQs
Universal MongoDb adapter for Node.js with a unified API.
We found that @dqcai/mongodb demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Add real-time Socket webhook events to your workflows to automatically receive software supply chain alert changes in real time.

Security News
ENISA has become a CVE Program Root, giving the EU a central authority for coordinating vulnerability reporting, disclosure, and cross-border response.

Product
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.