Guides

Use these guides when you already know the feature you want to turn on and need the smallest configuration shape, the key options, and the first place to look when something fails.

Connect to MongoDB

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');
await users.insertOne({ name: 'Ada', createdAt: new Date() });

await msq.close();
OptionRequiredWhat it does
typeOptionalMongoDB is the current runtime adapter. Use mongodb when you want to be explicit.
databaseNameYesDefault database used by collection() and model().
config.uriYesMongoDB connection string.

If it fails, check for INVALID_CONFIG when config.uri is missing and NOT_CONNECTED when a collection is accessed before connect().

Example source: examples/quick-start/basic-connect.ts

Enable Memory Cache

import MonSQLize from 'monsqlize';

const msq = new MonSQLize({
    type: 'mongodb',
    databaseName: 'app',
    config: { uri: 'mongodb://127.0.0.1:27017' },
    cache: {
        enabled: true,
        ttl: 60_000,
        maxEntries: 5_000,
        enableStats: true,
    },
});

await msq.connect();
OptionRequiredWhat it does
cache.enabledNoSet false to disable cache creation from this config block.
cache.ttl / cache.defaultTtlNoDefault TTL in milliseconds for cache entries created by the runtime.
cache.maxEntriesNoMaximum entry count for the memory cache.
cache.enableStatsNoEnables cache hit/miss statistics.

Memory cache needs no external service and is the quickest way to verify cached reads locally. Writes invalidate collection query cache; transaction writes flush pending invalidations after commit.

Example source: examples/cache/with-cache.ts

Enable Redis L2 Cache and Distributed Invalidation

import MonSQLize from 'monsqlize';

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

const msq = new MonSQLize({
    type: 'mongodb',
    databaseName: 'app',
    config: { uri: 'mongodb://127.0.0.1:27017' },
    cache: {
        memory: { maxEntries: 5_000, ttl: 30_000 },
        redis: { url: redisUrl, timeoutMs: 300 },
        distributed: {
            redisUrl,
            channel: 'app:cache:invalidate',
        },
    },
});

await msq.connect();
OptionRequiredWhat it does
cache.memoryNoLocal L1 cache settings.
cache.redis.urlYes for L2Redis connection used for the remote cache adapter.
cache.redis.timeoutMsNoTimeout for remote cache operations.
cache.distributed.redisUrlYes for Pub/Sub when no Redis instance is suppliedRedis connection used by distributed invalidation Pub/Sub.
cache.distributed.redisAlternativeExisting Redis-like instance for Pub/Sub.
cache.distributed.channelNoPub/Sub channel shared by all instances.

Keep the Redis URL in a variable when both L2 cache and distributed invalidation use the same Redis endpoint. The runtime does not infer cache.distributed.redisUrl from cache.redis.url; provide both values or pass a Redis instance to cache.distributed.redis.

Example source: examples/docs/cache-multilevel.ts

Connect Through an SSH Tunnel

import MonSQLize from 'monsqlize';

const msq = new MonSQLize({
    type: 'mongodb',
    databaseName: 'app',
    config: {
        uri: 'mongodb://mongo.internal:27017/app',
        ssh: {
            host: 'bastion.example.com',
            username: 'deploy',
            privateKeyPath: '~/.ssh/id_rsa',
        },
    },
});

await msq.connect();
OptionRequiredWhat it does
config.uriYesMongoDB URI as seen from the SSH target network.
config.ssh.hostYesBastion host.
config.ssh.usernameYesSSH username.
config.ssh.privateKeyPathUsuallyPrivate key path for key-based auth.

When config.ssh is present, monSQLize opens a local tunnel before connecting to MongoDB. If the connection fails, check SSH credentials first, then MongoDB reachability from the bastion network.

Related docs: ssh-tunnel.md

Configure Multiple Connection Pools

import MonSQLize from 'monsqlize';

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

await msq.connect();
const reports = msq.pool('analytics').collection('reports');
OptionRequiredWhat it does
pools[].nameYesStable pool name used by pool(name).
pools[].uriYesMongoDB URI for that pool.
pools[].roleNoDescribes primary, secondary, analytics, archive, or custom use.
poolStrategyNoSelection strategy for pool routing.
poolFallbackNoFallback behavior when a selected pool is unavailable.

Configuration errors throw INVALID_CONFIG; unknown pool names throw POOL_NOT_FOUND; unavailable pools throw INVALID_OPERATION.

Example sources: examples/docs/pool.ts and examples/docs/multi-pool-health-check.ts

Enable the Model Layer

import MonSQLize, { Model } from 'monsqlize';

Model.define('users', {
    schema: (s) => s({
        name: 'string:1-64!',
        email: 'email!',
    }),
});

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

await msq.connect();
const User = msq.model('users');
await User.insertOne({ name: 'Ada', email: 'ada@example.com' });
OptionRequiredWhat it does
Model.define(name, config)YesRegisters the model definition before runtime binding.
schema: (s) => s(...)UsuallyCurrent recommended schema callback style.
schemaDslNoRuntime options, extensions, injected runtime, or explicit validation disablement.
writePathPolicyNoUse model-only when selected namespaces must go through Model writes.

Model schema callbacks use the isolated schema-dsl/runtime owned by the MonSQLize instance. If your application owns custom schema-dsl types or messages, configure that runtime directly and inject it with schemaDsl: { runtime }.

Example source: examples/docs/model.ts

Troubleshoot by Error Code

import { ErrorCodes } from 'monsqlize';

try {
    await msq.connect();
} catch (error) {
    const code = (error as { code?: string }).code;
    if (code === ErrorCodes.INVALID_CONFIG) {
        console.error('Check the MonSQLize constructor options');
    } else if (code === ErrorCodes.CONNECTION_FAILED) {
        console.error('Check MongoDB network, authentication, and URI');
    } else {
        throw error;
    }
}
CodeUsual causeFirst check
INVALID_CONFIGMissing or malformed runtime optionsConstructor options and feature-specific config blocks
CONNECTION_FAILEDMongoDB or SSH connection failureNetwork, credentials, URI, and SSH tunnel reachability
NOT_CONNECTEDData API used before connect()Runtime lifecycle
POOL_NOT_FOUNDUnknown pool namepools[].name and msq.pool(name)

More details: error-codes.md