npm package: @qcksys/mongodb-ts-gen
Description: Generate TypeScript types and Zod v4 schemas from MongoDB collection metadata
Latest version: 0.1.0

# @qcksys/mongodb-ts-gen

Generate TypeScript types and Zod v4 schemas from MongoDB collection metadata.

Connects to a live MongoDB instance, samples documents, reads JSON Schema validators, and outputs strongly-typed interfaces or type aliases — with optional Zod v4 runtime schemas, CRUD variants, and a typed MongoDB client wrapper.

## Installation

```bash
pnpm add -D @qcksys/mongodb-ts-gen
```

## Quick Start

### Config file

Create `mongodb-ts-gen.config.ts`:

```ts
import { defineConfig } from "@qcksys/mongodb-ts-gen";

export default defineConfig({
    uri: "mongodb://localhost:27017",
    outDir: "./generated",
    zod: true,
    crud: true,
    typedClient: true,
    databases: {
        include: ["myapp"],
    },
});
```

Then run:

```bash
pnpx mongodb-ts-gen
```

### CLI flags

```bash
pnpx mongodb-ts-gen --uri mongodb://localhost:27017 --out-dir ./generated --zod --crud --typed-client
```

### Programmatic API

```ts
import { generate } from "@qcksys/mongodb-ts-gen";

const files = await generate({
    uri: "mongodb://localhost:27017",
    outDir: "./generated",
    databases: { include: ["myapp"] },
    zod: true,
    crud: true,
    typedClient: true,
});
```

## Configuration

| Option             | Type                    | Default       | Description                            |
| ------------------ | ----------------------- | ------------- | -------------------------------------- |
| `uri`              | `string`                | —             | MongoDB connection URI (required)      |
| `outDir`           | `string`                | —             | Output directory (required)            |
| `fileExtension`    | `'.ts' \| '.d.ts'`      | `'.ts'`       | Output file extension                  |
| `typeStyle`        | `'interface' \| 'type'` | `'interface'` | Generate interfaces or type aliases    |
| `zod`              | `boolean \| ZodConfig`  | `false`       | Generate Zod v4 schemas                |
| `crud`             | `boolean \| CrudConfig` | `false`       | Generate insert/update/delete variants |
| `typedClient`      | `boolean`               | `false`       | Generate typed MongoDB client wrapper  |
| `naming`           | `NamingConfig`          | see below     | Customize generated names              |
| `databases`        | `FilterConfig`          | `{}`          | Include/exclude databases              |
| `collections`      | `FilterConfig`          | `{}`          | Include/exclude collections            |
| `sampleSize`       | `number`                | `100`         | Documents to sample per collection     |
| `objectIdAsString` | `boolean`               | `true`        | Represent ObjectId as `string`         |
| `dateAsString`     | `boolean`               | `false`       | Represent Date as `string`             |

### CRUD Variants

When `crud: true`, separate types and schemas are generated for each collection:

| Variant    | Behavior                           | Default type name | Default schema name |
| ---------- | ---------------------------------- | ----------------- | ------------------- |
| **base**   | All fields as-is                   | `Users`           | `UsersSchema`       |
| **insert** | Omits `_id`, keeps required fields | `InsertUsers`     | `InsertUsersSchema` |
| **update** | Omits `_id`, all fields optional   | `UpdateUsers`     | `UpdateUsersSchema` |
| **delete** | Only `_id` field                   | `DeleteUsers`     | `DeleteUsersSchema` |

Select specific variants:

```ts
defineConfig({
    crud: { enabled: true, variants: ["insert", "update"] },
});
```

### Naming

Customize generated names with `prefix`, `suffix`, or a `transform` function. Configure per category (types vs schemas) and per variant:

```ts
defineConfig({
    naming: {
        types: {
            base: { suffix: "Doc" },
            insert: { prefix: "Create" },
            update: { transform: (name) => `Patch${name}` },
        },
        schemas: {
            base: { suffix: "Validator" },
            insert: { transform: (name) => `create${name}Schema` },
        },
    },
});
```

When `transform` is provided, it takes precedence over `prefix`/`suffix`. Transforms require a `.ts`/`.js` config file (not JSON).

### Typed Client

When `typedClient: true`, a `typed-client.ts` file is generated per database:

```ts
import type { Db, Collection } from "mongodb";
import type { Users } from "./users";
import type { Posts } from "./posts";

export interface TypedCollections {
    users: Collection<Users>;
    posts: Collection<Posts>;
}

export function typedDb(db: Db): TypedCollections {
    return {
        users: db.collection<Users>("users"),
        posts: db.collection<Posts>("posts"),
    };
}
```

Usage:

```ts
import { MongoClient } from "mongodb";
import { typedDb } from "./generated";

const client = new MongoClient("mongodb://localhost:27017");
const db = typedDb(client.db("myapp"));

const user = await db.users.findOne({ email: "alice@test.com" }); // typed as Users | null
await db.posts.insertOne({ title: "Hello", body: "World" }); // type-checked
```

### Filters

Both `databases` and `collections` support glob patterns (`*` and `?`):

```ts
defineConfig({
    databases: { include: ["myapp_*"], exclude: ["myapp_test"] },
    collections: { exclude: ["system*", "migrations"] },
});
```

## Output Structure

With all features enabled for a `users` collection:

```
generated/
  users.ts              # base type (Users)
  users.schema.ts       # base Zod schema (UsersSchema)
  users.insert.ts       # InsertUsers (no _id)
  users.insert.schema.ts
  users.update.ts       # UpdateUsers (all optional, no _id)
  users.update.schema.ts
  users.delete.ts       # DeleteUsers (only _id)
  users.delete.schema.ts
  typed-client.ts       # typedDb() wrapper
  index.ts              # barrel exports
```

## CLI Reference

```
Usage: mongodb-ts-gen [options]

Options:
  -c, --config <path>      path to config file (.ts, .js, or .json)
  -u, --uri <uri>          MongoDB connection URI
  -o, --out-dir <path>     output directory
  --file-extension <ext>   output file extension (.ts or .d.ts)
  --type-style <style>     interface or type
  --zod                    generate Zod v4 schemas
  --crud                   generate CRUD variants (insert/update/delete)
  --typed-client           generate typed MongoDB client wrapper
  --sample-size <n>        documents to sample per collection
  --object-id-as-string    represent ObjectId as string
  --date-as-string         represent Date as string
  --include-db <pattern>   include database (repeatable)
  --exclude-db <pattern>   exclude database (repeatable)
  --include-col <pattern>  include collection (repeatable)
  --exclude-col <pattern>  exclude collection (repeatable)
  -h, --help               display help for command
```

Config file auto-discovery order: `mongodb-ts-gen.config.ts` > `.js` > `.mjs` > `.json`

## Development

```bash
pnpm install
pnpm test             # run unit + integration tests (requires Docker)
pnpm check            # lint + format + type-check (oxlint/oxfmt)
pnpm build            # build library
pnpm changeset        # create a changeset
pnpm version          # bump versions from changesets
pnpm release          # build + publish to npm
```

## License

MIT