完整配置参考

本页是 new MonSQLize(options) 的公开配置参考,只说明构造函数配置。find(..., { cache, maxTimeMS }) 这类方法级选项放在对应 API 文档中说明。

当你需要确认下面这些问题时,优先看本页:

  • 最小可用配置怎么写?
  • 哪些字段可以全局配置?
  • MongoDB、缓存、Redis、Model、同步、连接池、日志、分页应该如何组合?
  • 哪些是默认值,哪些会在运行时校验?

最小配置

import MonSQLize from 'monsqlize';

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'app',
  config: {
    uri: 'mongodb://127.0.0.1:27017'
  }
});

await msq.connect();

const users = msq.collection('users');
const list = await users.find({ status: 'active' }).toArray();

await msq.close();

当前 runtime 要求显式传入 type: 'mongodb'databaseName 建议显式配置;如果省略,runtime 会按 databasedatabaseNamedefault 的顺序解析默认数据库名。

生产配置示例

import MonSQLize from 'monsqlize';

const redisUrl = 'redis://127.0.0.1:6379/0';

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: {
    uri: 'mongodb://mongo.internal:27017/shop',
    options: {
      maxPoolSize: 20,
      minPoolSize: 2,
      serverSelectionTimeoutMS: 5000
    }
  },

  maxTimeMS: 3000,
  findLimit: 500,
  findMaxLimit: 10000,
  findMaxSkip: 50000,
  findPageMaxLimit: 500,
  slowQueryMs: 500,

  cursorSecret: 'replace-with-a-stable-secret',
  requireCursorSecret: true,

  cache: {
    memory: {
      maxEntries: 100000,
      defaultTtl: 60000,
      enableStats: true
    },
    redis: {
      url: redisUrl,
      timeoutMs: 300,
      prefix: 'shop:'
    },
    distributed: {
      redisUrl,
      channel: 'shop:cache:invalidate',
      instanceId: 'api-1'
    }
  },
  cacheAutoInvalidate: true,

  logger: console,

  slowQueryLog: {
    enabled: true,
    storage: {
      type: 'mongodb',
      useBusinessConnection: true,
      database: 'ops',
      collection: 'slow_queries',
      ttl: 7 * 24 * 3600
    }
  },

  models: {
    path: './models',
    pattern: '*.model.{js,mjs,cjs}',
    recursive: false
  },
  autoIndex: false,

  writePathPolicy: {
    default: 'allow-both'
  }
});

Redis 二级缓存和分布式失效可以共用同一个 Redis URL。二者职责不同:二级缓存存储查询结果,cache.distributed 使用 Pub/Sub 做跨实例失效广播。

顶层配置项

配置项类型默认值说明
type'mongodb'当前 runtime 必填。
databaseNamestringalias fallback 后为 'default'默认数据库名。
databasestringdatabaseName 的 alias,优先级高于 databaseName
configMongoConnectConfigMongoDB 连接配置。
cacheMemoryCacheCacheLikeMultiLevelCacheOptions 或普通 cache configmemory cache查询缓存后端。
cacheAutoInvalidatebooleanfalsemonSQLize 写入后自动失效集合读缓存。
loggerLoggerLike | nullnull自定义 logger,必须暴露 debuginfowarnerror
schemaDslfalse | SchemaDslRuntimeConfig隔离 runtimeModel schema-dsl runtime 接入配置。
modelsstring | { path, pattern?, recursive? }连接时自动加载 Model 定义文件。
autoIndexboolean | objecttrue控制 Model 自动创建索引。
writePathPolicyWritePathPolicyOptionsallow-bothcollection 与 Model 写路径策略。
poolsPoolConfig[]额外 MongoDB 连接池。
poolStrategyPoolStrategymanager 默认值连接池选择策略。
poolFallbackboolean | objectmanager 默认值连接池失败后的 fallback 行为。
maxPoolsCountnumbermanager 默认值最大连接池数量。
transactionobjectmanager 默认值全局事务默认值与统计配置。
syncSyncConfigdisabledChange Stream 同步配置。
slowQueryLogboolean | Partial<SlowQueryLogConfig>disabled慢查询日志持久化配置。
maxTimeMSnumber2000全局查询超时时间,单位毫秒。
findLimitnumber500调用方未指定时的 find() 默认 limit。
findMaxLimitnumber10000显式 find().limit(n) 上限;limit(0) 保留 MongoDB 无限制语义。
findMaxSkipnumber50000显式 find().skip(n)offsetJump.maxSkip 上限。
findPageMaxLimitnumber500findPage() 最大 limit,超过后会被钳制。
slowQueryMsnumber500慢查询检测与慢查询日志默认阈值。
namespace{ scope?, instanceId? }{ scope: 'database' }缓存命名空间隔离配置。
cursorSecretstringfindPage() 游标 token 的 HMAC 密钥。
requireCursorSecretbooleanfalse要求配置 cursorSecret 后才能使用 findPage()
cursorSecretWarning'off' | 'production' | 'always''production'未配置 cursorSecret 时的启动告警策略。
cursorTypesRecord<string, CursorValueType>解码游标值时的字段类型提示。
cursorValueNormalizerCursorValueNormalizer自定义游标值归一化函数。
log.slowQueryTag{ event?, code? }{ event: 'slow_query', code: 'SLOW_QUERY' }慢查询事件 tag 字段。
log.formatSlowQuery(meta) => unknown慢查询事件 metadata 格式化函数。
autoConvertObjectIdboolean | object | field mapMongoDB 下为 true自动把合法 24 位 hex 字符串转换为 ObjectId
countQueueboolean | objectenabled高并发下批处理 count 操作。

Mongo 连接配置

config 会传给 MongoDB adapter,并参与可选 SSH / memory-server 初始化。

配置项类型说明
config.uristringMongoDB 连接 URI。除非使用 useMemoryServer,否则需要配置。
config.optionsMongoClientOptionsMongoDB driver 选项,例如 maxPoolSizeserverSelectionTimeoutMS、读写关注。
config.readPreferenceMongoDB read preference会合并到 MongoDB client options。
config.useMemoryServerboolean测试时自动启动 mongodb-memory-server
config.memoryServerOptionsobjectmemory-server 的 instancebinary 配置。
config.sshSSHConfig堡垒机隧道配置。
config.remoteHost / config.remotePortstring / numberSSH 服务器视角下的 MongoDB host / port。
config.mongoHost / config.mongoPortstring / numberremoteHost / remotePort 的 alias。
const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'private_app',
  config: {
    uri: 'mongodb://mongo.internal:27017/private_app',
    ssh: {
      host: 'bastion.example.com',
      port: 22,
      username: 'deploy',
      privateKeyPath: '~/.ssh/id_rsa'
    },
    remoteHost: 'mongo.internal',
    remotePort: 27017
  }
});

缓存配置

查询缓存是按查询启用的。全局 cache 只决定“某个查询要求缓存时,缓存结果存在哪里”。

在单次查询上使用 cache: 0 可禁用该查询缓存。构造函数层面如需禁用 cache backend,使用 cache: { enabled: false }。不要把 boolean 作为构造函数 cache 配置传入。

内存缓存

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  cache: {
    maxEntries: 100000,
    maxMemory: 0,
    defaultTtl: 60000,
    enableStats: true,
    enableTags: false,
    cleanupInterval: 60000
  }
});
配置项说明
cache.maxEntries最大缓存条目数。
cache.maxMemory最大内存字节数,0 表示不限制。
cache.defaultTtlset 操作未传 TTL 时使用的默认 TTL,单位毫秒。
cache.enableStats开启命中、未命中、淘汰等统计。
cache.enableTags当 cache backend 支持时,开启 tag 失效。
cache.cleanupIntervalTTL 清理周期,单位毫秒。
cache.enabled设为 false 时禁用该 cache backend。

Redis 二级缓存

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  cache: MonSQLize.createRedisCacheAdapter('redis://127.0.0.1:6379/0')
});

本地 + Redis 双层缓存推荐使用 memory + redis 声明式写法:

const redisUrl = 'redis://127.0.0.1:6379/0';

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  cache: {
    memory: { maxEntries: 10000, defaultTtl: 60000 },
    redis: { url: redisUrl, timeoutMs: 300, prefix: 'shop:' },
    policy: {
      writePolicy: 'both',
      backfillLocalOnRemoteHit: true
    }
  }
});

分布式缓存失效

cache.distributed 开启 Redis Pub/Sub 失效广播。runtime 不会自动从 cache.remote 推断 Pub/Sub 连接;需要显式配置 redisUrlurluri 或已有 Redis-like redis 实例。

const redisUrl = 'redis://127.0.0.1:6379/0';

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  cache: {
    memory: { maxEntries: 10000 },
    redis: { url: redisUrl },
    distributed: {
      redisUrl,
      channel: 'shop:cache:invalidate',
      instanceId: 'api-1',
      enabled: true
    }
  }
});

缓存失效是 best-effort,跨实例最终收敛。MongoDB 写入成功后,如果后续缓存失效或分布式广播失败,runtime 不会回滚数据库写入。

Logger 配置

可以传 consolenull,或暴露四个日志方法的对象。{ level: 'debug' } 这类对象不会生效,因为它不满足 logger 接口。

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  logger: {
    debug: (...args) => console.debug(...args),
    info: (...args) => console.info(...args),
    warn: (...args) => console.warn(...args),
    error: (...args) => console.error(...args)
  }
});

Model 与 schema-dsl 配置

Model 层默认使用隔离的 schema-dsl/runtime。只有在需要注入已有 runtime、注册扩展、传入 runtime options 或显式关闭 schema-dsl 校验时,才需要配置 schemaDsl

import { createRuntime } from 'schema-dsl/runtime';

const schemaRuntime = createRuntime({
  messages: {
    required: 'Required field'
  }
});

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  schemaDsl: {
    runtime: schemaRuntime
  }
});
配置项说明
schemaDsl: false关闭 Model schema-dsl 编译与校验。
schemaDsl.enabled设为 false 时禁用,但保留对象结构。
schemaDsl.runtime注入已有 schema-dsl runtime,monSQLize 使用它但不负责 dispose。
schemaDsl.optionsmonSQLize 自行创建 runtime 时传入的 options。
schemaDsl.extensionsModel schema 编译前注册的扩展定义。
models自动加载 Model 定义文件,支持路径字符串或 { path, pattern, recursive }
autoIndex全局 Model 自动索引创建控制。

写路径策略

默认情况下,collection 与 Model 写入都可用。如果某些命名空间必须经过 Model hooks、默认值、时间戳、版本与软删除规则,可以配置 model-only

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  writePathPolicy: {
    default: 'model-only',
    namespaces: {
      'shop.audit_logs': 'allow-both'
    }
  }
});

详见 写路径策略

连接池配置

当服务需要具名数据库连接时,在构造函数中配置 pools

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'main',
  config: { uri: 'mongodb://primary:27017/main' },
  pools: [
    {
      name: 'analytics',
      uri: 'mongodb://analytics:27017/main',
      role: 'analytics',
      tags: ['reporting'],
      options: { maxPoolSize: 5 }
    }
  ],
  poolStrategy: 'auto',
  poolFallback: { enabled: true, fallbackStrategy: 'primary' },
  maxPoolsCount: 5
});

const reports = msq.pool('analytics').collection('reports');

详见 连接池配置

同步配置

sync 会接入 Change Stream fan-out manager。runtime 提供 at-least-once 语义,target 应保持幂等。可以用 sync.idempotency 减少重复 target 副作用。

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'main',
  config: { uri: 'mongodb://primary:27017/main?replicaSet=rs0' },
  sync: {
    enabled: true,
    collections: ['orders'],
    targets: [
      {
        name: 'backup',
        uri: 'mongodb://backup:27017',
        databaseName: 'backup',
        collections: ['orders']
      }
    ],
    resumeToken: {
      storage: 'file',
      path: './.sync-resume-token',
      strictLoad: true,
      strictSave: true,
      saveRetries: 2,
      saveRetryDelayMs: 100
    },
    idempotency: {
      enabled: true,
      keyPrefix: 'monsqlize:sync:idempotency',
      ttl: 24 * 3600 * 1000,
      markMode: 'success'
    }
  }
});

详见 Change Stream 同步

慢查询日志

slowQueryMs 控制 runtime 阈值;需要持久化聚合慢查询记录时配置 slowQueryLog

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  slowQueryMs: 500,
  log: {
    slowQueryTag: { event: 'slow_query', code: 'SLOW_QUERY' },
    formatSlowQuery: (meta) => meta
  },
  slowQueryLog: {
    enabled: true,
    storage: {
      type: 'mongodb',
      useBusinessConnection: true,
      database: 'ops',
      collection: 'slow_queries',
      ttl: 7 * 24 * 3600
    },
    filter: {
      minExecutionTimeMs: 1000,
      excludeCollections: ['healthchecks']
    }
  }
});

详见 慢查询日志

事务配置

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017/shop?replicaSet=rs0' },
  transaction: {
    enableRetry: true,
    maxRetries: 3,
    retryDelay: 100,
    retryBackoff: 2,
    defaultTimeout: 30000,
    lockMaxDuration: 30000,
    lockCleanupInterval: 60000
  }
});

事务缓存锁是进程内锁。跨实例关键流程应使用应用层幂等/fencing 或显式业务锁。

运行时校验

以下构造项会在实例创建时校验:

配置项最小值最大值
maxTimeMS1300000
findLimit110000
findMaxLimit1100000
findMaxSkip010000000
findPageMaxLimit110000

findLimit 还必须小于或等于 findMaxLimit

配置优先级

同一能力同时存在实例级与方法级配置时,方法级配置优先。

const msq = new MonSQLize({
  type: 'mongodb',
  databaseName: 'shop',
  config: { uri: 'mongodb://127.0.0.1:27017' },
  maxTimeMS: 3000
});

await msq.connect();

const users = msq.collection('users');

await users.find({}, { maxTimeMS: 5000 }); // 使用 5000。
await users.find({});                      // 使用 3000。

常见误区

误区正确写法
把 boolean 当作构造函数 cache 配置cache: { enabled: false },或查询级 { cache: 0 }
通过 cache type 字符串和 host/port 对象选择 RedisMonSQLize.createRedisCacheAdapter(redisUrl)cache.redis.url
只传 logger levellogger: console,或提供 debug/info/warn/error 方法
以为 remote cache 字段会自动创建 Pub/Sub显式配置 cache.distributed.redisUrl
省略 type显式设置 type: 'mongodb'

相关文档