
Security News
arXiv Is Rate Limiting Authors Following a Flood of AI Slop Submissions
arXiv now limits authors to two submissions a month as AI slop overwhelms moderators, delays good papers, and sparks debate over applying the limit to everyone.
A lightweight MongoDB ORM with multi-level caching, transaction support, distributed features, Saga distributed transactions, unified expression system with 122 operators, and universal function caching (100% MongoDB support)
当前: MongoDB增强层(10~100倍性能 · 企业特性 · 零学习成本)
未来: 让MySQL/PostgreSQL也能用MongoDB语法查询
monSQLize = MongoDB + SQL = 一套语法,多种数据库
npm install monsqlize
// ❌ MongoDB 原生驱动
const users = await collection.find({ status: 'active' }).toArray(); // 50ms
const product = await products.findOne({ _id: productId }); // 10ms
// ✅ monSQLize(启用缓存)
const users = await collection.find({ status: 'active' }, { cache: 60000 }); // 0.5ms ⚡ 100x faster
const product = await products.findOne({ _id: productId }, { cache: 60000 }); // 0.1ms ⚡ 100x faster
只需在初始化时配置缓存,业务代码一行不改,性能立即提升!
用MongoDB语法统一所有数据库查询
monSQLize = MongoDB + SQL = 统一查询语法
为MongoDB应用提供:
⚡ 智能缓存L1: 内存缓存 (LRU) |
🏢 企业特性分布式锁 |
🛠️ 增强方法56+个方法 |
革命性目标: 让MySQL/PostgreSQL也能用MongoDB语法
// 同一套代码,支持多种数据库
const users = await collection.find({
age: { $gte: 18 },
status: 'active'
});
// MongoDB - ✅ 当前已支持
// MySQL - 🎯 未来自动转换为: SELECT * FROM users WHERE age >= 18 AND status = 'active'
// PostgreSQL - 🎯 未来自动转换为: SELECT * FROM users WHERE age >= 18 AND status = 'active'
解决的核心痛点:
monSQLize方案:
了解更多: 📖 完整项目愿景文档
|
😫 数据库性能瓶颈
😫 代码重复繁琐
😫 多实例部署问题
|
✅ monSQLize 的解决方案
✅ monSQLize 的解决方案
✅ monSQLize 的解决方案
|
| 场景 | 优化前 | 优化后 | 提升 |
|---|---|---|---|
| 商品详情页 | 50ms/次 | 0.5ms/次 | 100x ⚡ |
| 用户列表 | 80ms/次 | 0.8ms/次 | 100x ⚡ |
| 订单统计 | 200ms/次 | 2ms/次 | 100x ⚡ |
| 批量插入 10万条 | 30s | 1.2s | 25x ⚡ |
缓存命中率:电商 85% · 内容平台 75% · 社交应用 80%
| 场景 | 说明 | 预期效果 |
|---|---|---|
| 高并发读取 | 商品详情、用户信息等热点数据 | 缓存命中率 70 |
| 复杂查询 | 聚合统计、关联查询 | 重复查询直接走缓存,避免重复计算 |
| 多实例部署 | 负载均衡、水平扩展 | Redis 广播保证缓存一致性 |
| 事务密集 | 订单、支付等业务 | 自动管理事务,优化只读操作 |
| 并发控制 | 库存扣减、定时任务 | 分布式锁解决复杂并发场景 |
| 场景 | 原因 | 建议 |
|---|---|---|
| 纯写入应用 | 大量写入,很少查询 | 缓存作用有限,使用原生驱动即可 |
| 实时性要求极高 | 必须每次查询最新数据 | 不启用缓存,或使用极短 TTL |
| 简单 CRUD | 简单应用,流量不大 | 原生驱动足够,无需引入复杂度 |
| 内存受限 | 服务器内存紧张 | 缓存会占用额外内存 |
连接管理 · ObjectId 自动转换 🆕 · 缓存系统 · 事务管理 · Model 层 · 业务锁 · SSH 隧道 · 分布式部署
find · findOne · findOneById · findByIds · findPage · count · distinct · watch ⭐
插入: insertOne · insertMany · insertBatch
更新: updateOne · updateMany · updateBatch · replaceOne · findOneAndUpdate · findOneAndReplace
删除: deleteOne · deleteMany · deleteBatch · findOneAndDelete
便利方法: upsertOne · incrementOne · findAndCount
aggregate · explain · 链式调用 ⭐ · 索引管理 · Count 队列 ⭐ · 慢查询日志 · 书签管理 · ESM 支持
完整文档索引: docs/INDEX.md - 60+ 篇详细文档
npm install monsqlize
自动安装的依赖:
mongodb - MongoDB 官方驱动schema-dsl - Schema 验证库(Model 层必需)ssh2 - SSH 隧道支持可选依赖:
ioredis - Redis 多层缓存(启用 L2 缓存需要)const MonSQLize = require('monsqlize');
// 1. 初始化并连接
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'mydb',
config: { uri: 'mongodb://localhost:27017' },
cache: { enabled: true, ttl: 60000 } // 启用缓存,60秒过期
});
await msq.connect();
// 2. 获取集合
const users = msq.collection('users');
// 3. 基础查询(自动缓存)
const user = await users.findOne({ email: 'test@example.com' });
// 4. 插入数据
await users.insertOne({
username: 'john',
email: 'john@example.com',
createdAt: new Date()
});
// 5. 更新数据(自动清除缓存)
await users.updateOne(
{ email: 'test@example.com' },
{ $set: { lastLogin: new Date() } }
);
// 6. 便利方法(自动转换ObjectId)
const userById = await users.findOneById('507f1f77bcf86cd799439011');
// 7. 关闭连接
await msq.close();
就这么简单! 完全兼容MongoDB原生API,只需初始化时启用缓存,业务代码零改动。
如果需要 Schema验证、Populate关联查询、Hooks生命周期 等 ORM 特性,可以使用 Model 层。
📦 依赖说明: Model 层需要
schema-dsl包支持(已随 monsqlize 自动安装,无需额外操作)
Model 层有两种使用方式,二者互斥,选其一即可:
| 方式 | 适合场景 |
|---|---|
手动注册(Model.define()) | 少量 Model、测试环境、需要精确控制加载顺序 |
自动加载(models: 配置项) | 生产环境,Model 文件统一放在一个目录下 |
const MonSQLize = require('monsqlize');
const { Model } = MonSQLize;
// 1. 先在 connect() 之前调用 Model.define() 注册所有 Model
Model.define('users', {
schema: (dsl) => dsl({
username: 'string:3-32!',
email: 'email!',
password: 'string:6-!',
age: 'number:0-120'
}),
relations: {
posts: { from: 'posts', localField: '_id', foreignField: 'userId', single: false }
},
hooks: (model) => ({
insert: { before: async (ctx, doc) => { doc.createdAt = new Date(); return doc; } }
}),
methods: (model) => ({
instance: { checkPassword(password) { return this.password === password; } },
static: { async findByUsername(username) { return await model.findOne({ username }); } }
})
});
Model.define('posts', {
schema: (dsl) => dsl({ title: 'string:1-200!', content: 'string!', userId: 'string!' })
});
// 2. 创建实例并连接
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'mydb',
config: { uri: 'mongodb://localhost:27017' },
cache: { enabled: true }
});
await msq.connect();
// 3. 获取 Model 并使用
const User = msq.model('users');
将每个 Model 单独放在一个文件里,connect() 时自动扫描目录加载,无需手动 Model.define():
// app.js
const path = require('path');
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'mydb',
config: { uri: 'mongodb://localhost:27017' },
// 推荐用绝对路径,避免受 process.cwd() 影响
models: path.join(__dirname, 'models')
// 或完整配置:
// models: { path: path.join(__dirname, 'models'), pattern: '*.model.js', recursive: true }
});
await msq.connect(); // ← 自动扫描 models/*.model.{js,ts,mjs,cjs}
const User = msq.model('users'); // 直接使用,无需 Model.define()
相对路径(如
'./models')以process.cwd()为基准,即 Node.js 进程的启动目录。为避免歧义,推荐始终使用path.join(__dirname, 'models')这样的绝对路径。
// models/user.model.js ← 每个 Model 独立一个文件
module.exports = {
name: 'users', // 集合名称(必需)
schema: (dsl) => dsl({
username: 'string:3-32!',
email: 'email!'
}),
methods: (model) => ({
static: {
async findByUsername(username) { return await model.findOne({ username }); }
}
})
};
详细说明(完整配置项、文件格式、错误处理)见 docs/model.md — Model 自动加载
// ✅ Schema 验证自动生效
try {
await User.insertOne({
username: 'jo', // ❌ 太短,验证失败
email: 'invalid-email', // ❌ 邮箱格式错误
age: 25
});
} catch (err) {
console.error(err.code); // 'VALIDATION_ERROR'
console.error(err.errors); // 详细的验证错误
}
// ✅ 正确的数据
const user = await User.insertOne({
username: 'john',
email: 'john@example.com',
password: 'secret123',
age: 25
// createdAt 由 hook 自动添加
});
// 使用自定义方法
const foundUser = await User.findByUsername('john');
if (foundUser.checkPassword('secret123')) {
console.log('登录成功');
}
// Populate 关联查询(自动填充用户的文章)
const userWithPosts = await User.findOne({ username: 'john' })
.populate('posts');
console.log(userWithPosts.posts); // [{ title: '...', content: '...' }, ...]
// 禁用验证(特殊场景)
await User.insertOne(doc, { skipValidation: true });
Model 层特性:
schema-dsl 库,v1.0.7 默认启用)connection: { pool?, database? } 绑定指定连接池和/或数据库(v1.2.2+)数据源绑定示例(v1.2.2+):
// 在多连接池场景中,将 Model 绑定到指定的连接池 + 数据库
const msq = new MonSQLize({
uri: 'mongodb://localhost:27017',
databaseName: 'main_db',
pools: [{ name: 'analytics', uri: 'mongodb://analytics-host:27017' }]
});
// 绑定到不同数据库(使用默认连接池)
Model.define('AuditLog', {
schema: (dsl) => dsl({ action: 'string!', userId: 'string!' }),
connection: { database: 'audit_db' }
});
// 绑定到不同连接池 + 不同数据库
Model.define('AnalyticsReport', {
schema: (dsl) => dsl({ reportId: 'string!', data: 'object' }),
connection: { pool: 'analytics', database: 'reports_db' }
});
// 调用时自动路由,无需手动切换
const AuditLogModel = msq.model('AuditLog'); // → audit_db(默认池)
const ReportModel = msq.model('AnalyticsReport'); // → reports_db(analytics 池)
const UserModel = msq.model('users'); // → main_db(原逻辑,向后兼容)
📖 详细文档:Model 层完整指南 | Populate API | Hooks API | Schema 验证
// 原来的代码
const { MongoClient } = require('mongodb');
const client = await MongoClient.connect('mongodb://localhost:27017');
const db = client.db('mydb');
const users = db.collection('users');
// 迁移后(只需改初始化)
const MonSQLize = require('monsqlize');
const msq = new MonSQLize({
type: 'mongodb',
databaseName: 'mydb', // 数据库名称
config: { uri: 'mongodb://localhost:27017' },
cache: { enabled: true } // 启用缓存
});
await msq.connect();
const users = msq.collection('users');
// ✅ 后续代码完全不变
const user = await users.findOne({ email: 'test@example.com' });
52个测试(100% 通过),为任意异步函数添加缓存能力,性能提升50000x!
|
🆕 装饰器模式
|
核心优势
性能提升:
|
FunctionCache 类管理:
const { FunctionCache } = require('monsqlize');
const fnCache = new FunctionCache(msq, {
namespace: 'myApp',
defaultTTL: 60000
});
// 注册多个函数
fnCache.register('getUserProfile', getUserProfileFn);
fnCache.register('getOrderStats', getOrderStatsFn);
// 执行
await fnCache.execute('getUserProfile', 'user123');
// 失效缓存
await fnCache.invalidate('getUserProfile', 'user123');
// 查看统计
const stats = fnCache.getStats('getUserProfile');
console.log('命中率:', stats.hitRate);
122个操作符(100% MongoDB支持!新增49个函数),让MongoDB聚合查询像写SQL一样简单!
|
🆕 统一表达式语法
|
核心优势
支持的操作符分类:
|
更多示例:
// 条件判断 - 三元运算符
expr("score >= 90 ? 'A' : 'B'")
// 多分支条件 - SWITCH
expr("SWITCH(score >= 90, 'A', score >= 80, 'B', score >= 60, 'C', 'F')")
// 字符串处理
expr("UPPER(TRIM(email))")
expr("SPLIT(tags, ',')")
// 数组过滤(Lambda表达式)
expr("FILTER(items, item, item.price > 100)")
// 日期计算
expr("YEAR(createdAt) === 2024 && MONTH(createdAt) === 12")
// 完整聚合查询示例
await orders.aggregate([
{
$project: {
// 价格计算
finalPrice: expr("price * (1 - discount / 100)"),
// 日期提取
year: expr("YEAR(createdAt)"),
month: expr("MONTH(createdAt)"),
// 状态分类
statusLabel: expr("SWITCH(status === 'paid', 'Paid', status === 'pending', 'Pending', 'Cancelled')")
}
},
{
$group: {
_id: { year: '$year', month: '$month' },
totalOrders: expr("COUNT()"),
totalRevenue: expr("SUM(finalPrice)")
}
}
]);
|
特性
|
性能提升
|
// 一行代码启用缓存
const users = await collection.find({ status: 'active' }, { cache: 60000 });
// 自动管理事务生命周期
await db.withTransaction(async (tx) => {
// 只读操作会被优化(不加锁,减少 30% 访问)
const user = await users.findOne({ _id: userId }, { session: tx.session });
// 写操作自动加锁
await users.updateOne({ _id: userId }, { $inc: { balance: -100 } }, { session: tx.session });
// 自动提交 or 回滚
});
// 定义 Saga(跨服务事务)
msq.defineSaga({
name: 'create-order-with-payment',
steps: [
{
name: 'create-order',
execute: async (ctx) => {
const order = await createOrder(ctx.data);
// ✅ 可以保存字符串、对象、数组等任何类型
ctx.set('order', order); // 保存完整对象
return order;
},
compensate: async (ctx) => {
const order = ctx.get('order');
await cancelOrder(order.id);
}
},
{
name: 'charge-payment',
execute: async (ctx) => {
const charge = await stripe.charges.create({...});
ctx.set('charge', charge); // 保存完整对象
return charge;
},
compensate: async (ctx) => {
const charge = ctx.get('charge');
await stripe.refunds.create({ charge: charge.id });
}
}
]
});
// 执行 Saga(失败自动补偿)
const result = await msq.executeSaga('create-order-with-payment', data);
Saga 特性:
实时同步数据到备份库,基于 MongoDB Change Stream
const msq = new MonSQLize({
type: 'mongodb',
config: {
uri: 'mongodb://localhost:27017/main',
replicaSet: 'rs0' // 🔴 必须:Change Stream 需要 Replica Set
},
// 🆕 同步配置
sync: {
enabled: true,
targets: [
{
name: 'backup-main',
uri: 'mongodb://backup:27017/backup',
collections: ['users', 'orders']
}
]
}
});
await msq.connect();
// 正常使用,自动同步
await msq.collection('users').insertOne({ name: 'Alice' });
// ✅ 自动通过 Change Stream 同步到 backup-main
Change Stream 特性:
|
❌ 原生驱动
|
✅ monSQLize
代码减少 60~80%! |
🔥 ObjectId 自动转换 - 告别手动转换
// ❌ 原生驱动 - 每次都要转换
const { ObjectId } = require('mongodb');
await users.findOne({ _id: new ObjectId(userId) });
await users.find({ _id: { $in: ids.map(id => new ObjectId(id)) } }).toArray();
// ✅ monSQLize - 自动识别并转换
await users.findOneById(userId); // 自动转换字符串
await users.findByIds([id1, id2, id3]); // 批量自动转换
await users.findOne({ _id: userId }); // 查询时也自动转换
// 多实例部署,Redis 自动同步缓存
const db = new MonSQLize({
cache: {
distributed: {
enabled: true,
redis: redisInstance // 使用 Redis 广播缓存失效
}
}
});
// 实例 A 更新数据
await users.updateOne({ _id: userId }, { $set: { name: 'Bob' } });
// ⚡ 实例 B/C/D 的缓存自动失效
// 🔥 解决复杂业务场景的并发问题
// 场景1:库存扣减
await db.withLock(`inventory:${sku}`, async () => {
const product = await inventory.findOne({ sku });
const price = calculatePrice(product, user, coupon); // 复杂计算
if (user.balance < price) throw new Error('余额不足');
await inventory.updateOne({ sku }, { $inc: { stock: -1 } });
await users.updateOne({ userId }, { $inc: { balance: -price } });
await orders.insertOne({ userId, sku, price });
});
// 场景2:定时任务防重(多实例环境)
const lock = await db.tryAcquireLock('cron:daily-report');
if (lock) {
try {
await generateDailyReport(); // 只有一个实例执行
} finally {
await lock.release();
}
}
特性:基于 Redis · 自动重试 · TTL 防死锁 · 支持续期 · 降级策略
// 批量插入 10 万条数据
await users.insertBatch(documents, {
batchSize: 1000, // 每批 1000 条
retryTimes: 3, // 失败重试 3 次
onProgress: (stats) => {
console.log(`进度: ${stats.inserted}/${stats.total}`);
}
});
性能: 比原生 insertMany 快 10~50 倍 ⚡
// 千万级数据分页(游标分页,性能稳定)
const result = await users.findPage({
query: { status: 'active' },
page: 1000, // 第 1000 页
limit: 20,
totals: {
mode: 'async', // 异步统计总数
ttl: 300000 // 缓存 5 分钟
}
});
console.log(`总计: ${result.totals.total}, 共 ${result.totals.totalPages} 页`);
// 🆕 慢查询日志持久化存储(v1.3+)
const msq = new MonSQLize({
type: 'mongodb',
config: { uri: 'mongodb://localhost:27017/mydb' },
slowQueryMs: 500,
slowQueryLog: true // ✅ 零配置启用,自动存储到 admin.slow_query_logs
});
await msq.connect();
// 查询慢查询日志(支持去重聚合)
const logs = await msq.getSlowQueryLogs(
{ collection: 'users' },
{ sort: { count: -1 }, limit: 10 } // 查询高频慢查询Top10
);
// [{ queryHash: 'abc123', count: 2400, avgTimeMs: 520, maxTimeMs: 1200, ... }]
// 自动记录慢查询(原有功能)
// [WARN] Slow query { ns: 'mydb.users', duration: 1200ms, query: {...} }
// 健康检查
const health = await db.health();
// { status: 'ok', uptime: 3600, connections: 10 }
// 性能指标
const stats = await db.getStats();
// { queries: 10000, cacheHits: 9000, hitRate: 0.9 }
// 场景:数据库位于防火墙后,无法直接访问
const db = new MonSQLize({
type: 'mongodb',
config: {
// SSH隧道配置
ssh: {
host: 'bastion.example.com', // SSH服务器(跳板机)
port: 22,
username: 'deploy',
password: 'your-password', // ✅ 支持密码认证
// 或使用私钥认证(推荐)
// privateKeyPath: '~/.ssh/id_rsa',
},
// MongoDB连接配置(内网地址,自动从URI解析remoteHost和remotePort)
uri: 'mongodb://user:pass@internal-mongo:27017/mydb'
}
});
await db.connect(); // 自动建立SSH隧道
// 正常使用MongoDB,无需关心隧道细节
const users = db.collection('users');
const data = await users.findOne({});
await db.close(); // 自动关闭SSH隧道
特性:
解决混用 mongoose 和 monSQLize 时的 BSON 版本冲突问题。
// ❌ 问题场景:mongoose (bson@4.x/5.x) + monSQLize (bson@6.x)
const dataFromMongoose = await MongooseModel.findOne({ ... }).lean();
await msq.collection('orders').insertOne(dataFromMongoose);
// 错误:Unsupported BSON version, bson types must be from bson 6.x.x
// ✅ monSQLize v1.1.1+ 自动处理
const dataFromMongoose = await MongooseModel.findOne({ ... }).lean();
await msq.collection('orders').insertOne(dataFromMongoose);
// 成功:自动将旧版本 ObjectId 转换为 bson@6.x
特性:
兼容性:
| BSON 版本 | mongoose 版本 | 支持状态 |
|---|---|---|
| bson@4.x | mongoose@5.x | ✅ 完全支持 |
| bson@5.x | mongoose@6.x | ✅ 完全支持 |
| bson@6.x | mongoose@7.x | ✅ 原生支持 |
monSQLize 提供了一个轻量级的 Model 层,让你可以像使用 ORM 一样定义数据模型,同时保持 MongoDB 的灵活性。
📦 依赖说明: Model 层基于
schema-dsl库实现 Schema 验证,已随 monsqlize 自动安装。
const { Model } = require('monsqlize');
// 1. 定义 Model(集成 schema-dsl 验证)
Model.define('users', {
enums: {
role: 'admin|user|guest'
},
schema: function(dsl) {
return dsl({
username: 'string:3-32!',
email: 'email!',
role: this.enums.role.default('user'),
age: 'number:1-150'
});
},
options: {
timestamps: true, // 🆕 v1.0.3: 自动管理 createdAt/updatedAt
softDelete: true // 🆕 v1.0.3: 软删除(标记删除,支持恢复)
},
methods: (model) => ({
// 实例方法 - 注入到查询返回的文档对象
instance: {
isAdmin() {
return this.role === 'admin';
}
},
// 静态方法 - 挂载到 Model 实例
static: {
async findByEmail(email) {
return await model.findOne({ email });
}
}
}),
hooks: (model) => ({
// 生命周期钩子
insert: {
before: (ctx, docs) => {
// 自动添加时间戳
return { ...docs, createdAt: new Date() };
}
}
}),
indexes: [
{ key: { username: 1 }, unique: true },
{ key: { email: 1 }, unique: true }
]
});
// 2. 使用 Model
const db = new MonSQLize({ /* ... */ });
await db.connect();
const User = db.model('users');
// 自动 Schema 验证
const user = await User.insertOne({
username: 'john',
email: 'john@example.com',
age: 25
}); // ✅ 验证通过
// 使用实例方法
const admin = await User.findOne({ username: 'admin' });
console.log(admin.isAdmin()); // true
// 使用静态方法
const user = await User.findByEmail('john@example.com');
// 软删除(标记删除,可恢复)
await User.deleteOne({ _id: user._id });
// 查询(自动过滤已删除)
const users = await User.find({}); // 不包含已删除用户
// 查询包含已删除
const allUsers = await User.findWithDeleted({});
// 恢复已删除
await User.restore({ _id: user._id });
特性:
轻松处理集合之间的关联关系,支持 one-to-one 和 one-to-many。
// 1. 定义关系
Model.define('users', {
schema: (dsl) => dsl({
username: 'string!',
profileId: 'objectId'
}),
relations: {
// one-to-one: 用户 → 个人资料
profile: {
from: 'profiles', // 集合名
localField: 'profileId', // 本地字段
foreignField: '_id', // 外部字段
single: true // 返回类型
},
// one-to-many: 用户 → 文章列表
posts: {
from: 'posts',
localField: '_id',
foreignField: 'authorId',
single: false // 返回数组
}
}
});
// 2. 使用 populate
const user = await User.findOne({ username: 'john' })
.populate('profile') // 填充 profile
.populate('posts', { // 填充 posts
select: 'title content', // 只选择部分字段
match: { status: 'published' }, // 额外查询条件
sort: { createdAt: -1 }, // 排序
limit: 10 // 限制数量
});
// 3. 结果
{
_id: '...',
username: 'john',
profileId: '...',
profile: { // ← 自动填充
_id: '...',
bio: 'Software Engineer',
avatar: 'https://...'
},
posts: [ // ← 自动填充
{ _id: '...', title: 'Post 1', content: '...' },
{ _id: '...', title: 'Post 2', content: '...' }
]
}
支持的查询方法(全部 6 个):
find().populate() - 批量查询findOne().populate() - 单文档查询findByIds().populate() - 批量 ID 查询findOneById().populate() - 单 ID 查询findAndCount().populate() - 带计数查询findPage().populate() - 分页查询特点:
$lookup)注意:需要安装 schema-dsl 依赖:
npm install schema-dsl
在开发模式下,无需重启进程即可更新 Model 定义。
const { Model } = require('monsqlize');
// 注销 Model 定义(返回 boolean)
Model.undefine('users'); // true — 成功注销
Model.undefine('nonexistent'); // false — 不存在时不抛错
// 替换 Model 定义(undefine + define 的组合)
Model.redefine('users', {
schema: (dsl) => dsl({ username: 'string!', email: 'email!' })
});
// 批量热重载(重新加载所有 model 文件)
await msq._loadModels({ reload: true });
注意事项:
redefine() 若新定义校验失败,旧定义已被移除(不会回滚),调用方需 try/catchModelInstance 不受影响,热重载后应通过 db.model() 重新获取实例// 实时监听订单变化
const watcher = orders.watch([
{ $match: { 'fullDocument.status': 'pending' } }
]);
watcher.on('change', (change) => {
console.log('新订单:', change.fullDocument);
// 触发通知、更新统计、失效缓存等
});
// ✅ 自动处理:重连、错误恢复、缓存失效
特性: 支持聚合管道过滤 · 断点续传 · 自动失效相关缓存
// 高并发场景:100 个用户同时请求分页
const db = new MonSQLize({
countQueue: {
enabled: true, // 默认启用
concurrency: 8 // 同时最多 8 个 count
}
});
// ✅ 自动队列控制,防止 count 拖垮数据库
const result = await users.findPage({
query: { status: 'active' },
totals: { mode: 'async' } // 自动应用队列
});
效果: 数据库 CPU 从 100% → 30% · 其他查询不再超时
// jQuery 风格的链式调用
const result = await users
.find()
.filter({ age: { $gte: 18 } })
.sort({ createdAt: -1 })
.limit(10)
.cache(60000)
.exec();
// ✅ 代码更清晰、可读性更强
// 启用版本控制
Model.define('products', {
schema: (dsl) => dsl({ name: 'string!', stock: 'number!' }),
options: { optimisticLock: true }
});
// 自动版本检查和更新
await Product.updateOne(
{ _id: productId, __v: 1 }, // 要求版本为 1
{ $inc: { stock: -1 }, $inc: { __v: 1 } } // 自动递增版本
);
// ❌ 如果版本不匹配(被其他请求修改),更新失败
// ✅ 支持 import/export
import MonSQLize from 'monsqlize';
const db = new MonSQLize({ /* ... */ });
await db.connect();
// 🎯 完美支持 TypeScript
import type { Collection, MonSQLizeConfig } from 'monsqlize';
| 场景 | 原生驱动 | monSQLize (缓存) | 提升倍数 |
|---|---|---|---|
| 热点查询 (findOne) | 10ms | 0.1ms | 100x ⚡ |
| 列表查询 (find) | 50ms | 0.5ms | 100x ⚡ |
| 复杂聚合 (aggregate) | 200ms | 2ms | 100x ⚡ |
| 批量插入 (10万条) | 30s | 1.2s | 25x ⚡ |
结论: 在真实业务场景中,缓存命中率通常在 70~90%,性能提升 10~100 倍。
📦 MongoDB 原生功能✅ CRUD 操作
✅ 聚合 & 查询 ✅ 索引管理
✅ 事务支持
|
🚀 增强功能✅ 企业级多连接池 (v1.0.8+)
✅ Saga 分布式事务 (v1.1.0 计划)
✅ 智能缓存
✅ 便利方法 ✅ 性能优化
✅ 分布式支持
|
🛠️ 企业级特性✅ 运维监控
✅ 深度分页
✅ 数据库管理 ✅ 开发体验
|
| 特性 | MongoDB 原生 | monSQLize |
|---|---|---|
| API 兼容性 | ✅ 原生 | ✅ 100% 兼容原生,无需学习新 API |
| 智能缓存 | ❌ 需要自己实现 | ✅ 内置 TTL/LRU,开箱即用,10~100倍提升 |
| 性能 | ⭐⭐⭐ 基准性能 | ⭐⭐⭐⭐⭐ 缓存命中时性能提升 10~100 倍 |
| 事务支持 | ⭐⭐ 需要手动管理 | ⭐⭐⭐⭐⭐ 自动管理生命周期,优化只读操作 |
| 分布式部署 | ❌ 缓存不一致 | ✅ Redis 广播自动同步,保证一致性 |
| 便利方法 | ❌ 需要自己封装 | ✅ findOneById、findByIds、upsertOne 等 |
| 运维监控 | ⚠️ 需要额外配置 | ✅ 慢查询日志、性能统计,开箱即用 |
| 学习成本 | ⭐⭐⭐ MongoDB 语法 | ⭐ 零学习成本,API 完全一致 |
| 迁移成本 | - | ⭐ 只需修改初始化代码,业务代码不变 |
✅ 适合场景:
⚠️ 不适合场景:
// ❌ 原来的代码
const { MongoClient } = require('mongodb');
const client = await MongoClient.connect('mongodb://localhost:27017');
const db = client.db('mydb');
const users = db.collection('users');
// ✅ 迁移后的代码(只需改 3 行)
const MonSQLize = require('monsqlize'); // 1. 引入 monSQLize
const db = new MonSQLize({ // 2. 修改初始化
type: 'mongodb',
config: { uri: 'mongodb://localhost:27017/mydb' },
cache: { enabled: true } // 3. 启用缓存
});
await db.connect();
const users = db.collection('users');
// 🎉 后续所有代码不需要改动,性能提升 10~100 倍!
const user = await users.findOne({ email }); // 完全一样的 API
// ✅ 可以混用原生驱动和 monSQLize
const nativeClient = await MongoClient.connect('...');
const monsqlize = new MonSQLize({ cache: { enabled: true } });
// 性能敏感的查询用 monSQLize(启用缓存)
const hotData = await monsqlize.collection('products').find({}, { cache: 60000 });
// 简单查询用原生驱动
const coldData = await nativeClient.db('mydb').collection('logs').find({});
CRUD 操作:
Model 层:
便利方法:
其他功能:
| 环境 | 支持版本 |
|---|---|
| Node.js | 16.x, 18.x, 20.x, 21.x |
| MongoDB | 4.4+, 5.x, 6.x, 7.x |
| MongoDB Driver | 4.x, 5.x, 6.x, 7.x |
| 模块系统 | CommonJS, ESM |
我们欢迎所有形式的贡献!
# 克隆仓库
git clone https://github.com/vextjs/monSQLize.git
cd monSQLize
# 安装依赖
npm install
# 运行测试
npm test
# 运行基准测试
npm run benchmark
FAQs
TypeScript production data runtime layer for MongoDB today, with cache, transactions, pools, models, sync, and observability
The npm package monsqlize receives a total of 56 weekly downloads. As such, monsqlize popularity was classified as not popular.
We found that monsqlize 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.

Security News
arXiv now limits authors to two submissions a month as AI slop overwhelms moderators, delays good papers, and sparks debate over applying the limit to everyone.

Research
/Security News
A new GhostAction wave hits hundreds of GitHub repos, expanding CI/CD secret theft to cloud and AI credentials in source code and git history.

Research
/Security News
Tensorlake npm SDK version 0.5.144 was compromised in a ChainDrop / Shai-Hulud attack, delivering credential-stealing malware.