Skip to content

Tool to convert Zod schemas to draft 4 JSON schemas compatible with MongoDB validation.

Notifications You must be signed in to change notification settings

marcesengel/zod-to-mongodb-schema

Repository files navigation

Zod to MongoDB schema

Converts Zod schemas to MongoDB validation schemas. Inspired by zod-to-json-schema, but became a separate package as the overlap between what MongoDB uses and Draft 7 was deemed to little.

Usage

import { z } from 'zod'
import zodToMongoSchema from 'zod-to-mongodb-schema'
import { ObjectId } from 'wherever' // bson, mongodb, mongoose...

// should also check for typeof value, as isValid also accepts for example numbers
const zodObjectId = z.custom<ObjectId | string>(value => ObjectId.isValid(value))

const userSchema = z.object({
  _id: zodObjectId,
  name: z.string().min(3),
  dateOfBirth: z.date(),
})

const mongoUserSchema = zodToMongoSchema(userSchema, { zodObjectId })

with mongoUserSchema being

// TODO: insert result

Options

Name Required Type Description
zodObjectId Yes ZodAnyType The zod schema you use to validate object ids (for example `z.custom<ObjectId
onUnsupported No (default: 'warn') 'error' or 'warn' or 'no-op' How to handle unsupported validations (see below).

Supported validators

For each supported validator, all modifiers which can be implemented in MongoDB are supported (for example z.string().email() is supported by using the RegEx used by zod itself).

Not that unsupported validators can be used in your schema, they will result in {}. If you'd like to receive errors when you're using unsupported validators, see the options above.

Zod Supported Remarks
string() -
number() Uses bsonType: 'long' for .int().
object() Sets additionalProperties: false unless .passthrough() is specified.
bigint() The MongoDB driver doesn't support (de-)serializing BigInt.
boolean() -
date() min and max not supported by MongoDB.
undefined() Flagged as deprecated.
void() See above.
null() -
array() -
union() WIP -
discriminatedUnion() WIP -
intersection() WIP -
tuple() WIP -
record() WIP -
literal() WIP -
enum() Credit @exsjabe!
nativeEnum() WIP -
map() See bigint().
set() See bigint().
lazy() WIP -
promise() -
nan() WIP Might be possible by using bsonType: 'double' with enum: [ NaN ] but I have no idea how to serialize NaN.
never() WIP -
preprocess() WIP No-op.
refine() WIP No-op.
transform() WIP No-op.
function() WIP No validation besides it being a function.
symbol() See undefined().

About

Tool to convert Zod schemas to draft 4 JSON schemas compatible with MongoDB validation.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published