Client & Connections
Decision tree
Are you on Workers / Lambda / Edge / per-invocation runtime?
YES → serverless: true (factory)
NO → long-running Node server?
YES → uri + await createClient (singleton)
NO → scripts/CLI → uri mode or MongoClient directlyServerless mode
typescript
import { createClient, type SchemasToClient } from "mondel";
import { schemas } from "./schemas";
export type DbClient = SchemasToClient<typeof schemas>;
export const connect = createClient({
serverless: true,
schemas,
validation: "strict",
});
// Later:
const db = await connect(env.MONGODB_URI, {
// optional MongoClientOptions
maxPoolSize: 5,
});
try {
return await db.users.findMany({});
} finally {
await db.close();
}Client methods
| Method | Description |
|---|---|
db.<schemaName> | Collection proxy |
db.close() | Close underlying MongoClient |
db.getDb() | Native Db |
db.startSession(options?) | Transactions |
Node mode
typescript
const db = await createClient({
uri: process.env.MONGODB_URI!,
schemas,
validation: "strict",
options: {
maxPoolSize: 20,
},
});
// Reuse `db` for the process lifetime
// On shutdown:
await db.close();Multiple databases
Use separate clients, not a named-connection map:
typescript
const main = await createClient({ uri: process.env.MAIN_URI!, schemas: appSchemas });
const analytics = await createClient({
uri: process.env.ANALYTICS_URI!,
schemas: eventSchemas,
});Connection hygiene
| Environment | Guidance |
|---|---|
| Express / Fastify | One client at startup; close on SIGTERM |
| Cloudflare Workers | Factory in module scope; connect in fetch; prefer Atlas + reasonable pool |
| AWS Lambda | Reuse client across invocations when the runtime freezes the isolate; avoid connect+close every time if the platform reuses the process |
| High concurrency serverless | Watch Atlas connection limits; consider smaller maxPoolSize, Private Link, or a proxy |
Mondel does not implement its own pool — the official driver does. Pass MongoClientOptions through options (node) or the second argument of the serverless factory.
Deprecated: syncIndexes
typescript
// Avoid on the hot path
createClient({ syncIndexes: true, ... });Use:
bash
npx mondel push --uri "$MONGODB_URI" --schema ./dist/schemas.jsTyping the client
typescript
import type { SchemasToClient } from "mondel";
const schemas = [userSchema] as const;
type Db = SchemasToClient<typeof schemas>;
// Db["users"] has findOne, create, ...Without as const, TypeScript widens schema names and you lose precise db.users typing.
