@mirite/zod-to-mongoose 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ /// <reference types="mongoose/types/aggregate" />
2
+ /// <reference types="mongoose/types/callback" />
3
+ /// <reference types="mongoose/types/collection" />
4
+ /// <reference types="mongoose/types/connection" />
5
+ /// <reference types="mongoose/types/cursor" />
6
+ /// <reference types="mongoose/types/document" />
7
+ /// <reference types="mongoose/types/error" />
8
+ /// <reference types="mongoose/types/expressions" />
9
+ /// <reference types="mongoose/types/helpers" />
10
+ /// <reference types="mongoose/types/indexes" />
11
+ /// <reference types="mongoose/types/inferschematype" />
12
+ /// <reference types="mongoose/types/middlewares" />
13
+ /// <reference types="mongoose/types/models" />
14
+ /// <reference types="mongoose/types/mongooseoptions" />
15
+ /// <reference types="mongoose/types/pipelinestage" />
16
+ /// <reference types="mongoose/types/populate" />
17
+ /// <reference types="mongoose/types/query" />
18
+ /// <reference types="mongoose/types/schemaoptions" />
19
+ /// <reference types="mongoose/types/schematypes" />
20
+ /// <reference types="mongoose/types/session" />
21
+ /// <reference types="mongoose/types/types" />
22
+ /// <reference types="mongoose/types/utility" />
23
+ /// <reference types="mongoose/types/validation" />
24
+ /// <reference types="mongoose/types/virtuals" />
25
+
26
+ import * as Mongoose from 'mongoose';
27
+ import { z } from 'zod';
28
+ import { ZodBoolean } from 'zod';
29
+ import { ZodDate } from 'zod';
30
+ import { ZodDefault } from 'zod';
31
+ import { ZodNumber } from 'zod';
32
+ import { ZodObject } from 'zod';
33
+ import { ZodRawShape } from 'zod';
34
+ import { ZodString } from 'zod';
35
+ import { ZodTypeAny } from 'zod';
36
+ import { ZodUnion } from 'zod';
37
+
38
+ export declare type Check = "";
39
+
40
+ export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>, modelName: string, connection: Mongoose.Connection): {
41
+ schema: Mongoose.Schema;
42
+ model: Mongoose.Model<z.infer<typeof zodObject>>;
43
+ };
44
+
45
+ export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;
46
+
47
+ export declare type Field = {
48
+ _def: FieldDefinition;
49
+ checks?: Array<Check>;
50
+ defaultValue?: () => unknown;
51
+ };
52
+
53
+ export declare type FieldDefinition = {
54
+ typeName: string;
55
+ innerType?: Field;
56
+ description: string | undefined;
57
+ };
58
+
59
+ declare type SupportedPrimitive = ZodString | ZodNumber | ZodBoolean | ZodDate;
60
+
61
+ export declare type SupportedType = SupportedPrimitive | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
62
+
63
+ export { }
@@ -0,0 +1,63 @@
1
+ /// <reference types="mongoose/types/aggregate" />
2
+ /// <reference types="mongoose/types/callback" />
3
+ /// <reference types="mongoose/types/collection" />
4
+ /// <reference types="mongoose/types/connection" />
5
+ /// <reference types="mongoose/types/cursor" />
6
+ /// <reference types="mongoose/types/document" />
7
+ /// <reference types="mongoose/types/error" />
8
+ /// <reference types="mongoose/types/expressions" />
9
+ /// <reference types="mongoose/types/helpers" />
10
+ /// <reference types="mongoose/types/indexes" />
11
+ /// <reference types="mongoose/types/inferschematype" />
12
+ /// <reference types="mongoose/types/middlewares" />
13
+ /// <reference types="mongoose/types/models" />
14
+ /// <reference types="mongoose/types/mongooseoptions" />
15
+ /// <reference types="mongoose/types/pipelinestage" />
16
+ /// <reference types="mongoose/types/populate" />
17
+ /// <reference types="mongoose/types/query" />
18
+ /// <reference types="mongoose/types/schemaoptions" />
19
+ /// <reference types="mongoose/types/schematypes" />
20
+ /// <reference types="mongoose/types/session" />
21
+ /// <reference types="mongoose/types/types" />
22
+ /// <reference types="mongoose/types/utility" />
23
+ /// <reference types="mongoose/types/validation" />
24
+ /// <reference types="mongoose/types/virtuals" />
25
+
26
+ import * as Mongoose from 'mongoose';
27
+ import { z } from 'zod';
28
+ import { ZodBoolean } from 'zod';
29
+ import { ZodDate } from 'zod';
30
+ import { ZodDefault } from 'zod';
31
+ import { ZodNumber } from 'zod';
32
+ import { ZodObject } from 'zod';
33
+ import { ZodRawShape } from 'zod';
34
+ import { ZodString } from 'zod';
35
+ import { ZodTypeAny } from 'zod';
36
+ import { ZodUnion } from 'zod';
37
+
38
+ export declare type Check = "";
39
+
40
+ export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>, modelName: string, connection: Mongoose.Connection): {
41
+ schema: Mongoose.Schema;
42
+ model: Mongoose.Model<z.infer<typeof zodObject>>;
43
+ };
44
+
45
+ export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;
46
+
47
+ export declare type Field = {
48
+ _def: FieldDefinition;
49
+ checks?: Array<Check>;
50
+ defaultValue?: () => unknown;
51
+ };
52
+
53
+ export declare type FieldDefinition = {
54
+ typeName: string;
55
+ innerType?: Field;
56
+ description: string | undefined;
57
+ };
58
+
59
+ declare type SupportedPrimitive = ZodString | ZodNumber | ZodBoolean | ZodDate;
60
+
61
+ export declare type SupportedType = SupportedPrimitive | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
62
+
63
+ export { }
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";var s=Object.create;var d=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var S=(e,o)=>{for(var n in o)d(e,n,{get:o[n],enumerable:!0})},r=(e,o,n,t)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of l(o))!h.call(e,a)&&a!==n&&d(e,a,{get:()=>o[a],enumerable:!(t=u(o,a))||t.enumerable});return e};var b=(e,o,n)=>(n=e!=null?s(m(e)):{},r(o||!e||!e.__esModule?d(n,"default",{value:e,enumerable:!0}):n,e)),Z=e=>r(d({},"__esModule",{value:!0}),e);var w={};S(w,{createSchema:()=>f});module.exports=Z(w);var c=b(require("mongoose"),1);function f(e,o,n){let t={};for(let i in e.shape){let p=e.shape[i];t[i]=T(i,p)}let a=new c.Schema(t);return!n||!o?a:{schema:a,model:n.model(o,a)}}function y(e){return e._def.typeName==="ZodObject"}function T(e,o){let n=g(o),t;switch(n.definition._def.typeName){case"ZodString":t=String;break;case"ZodNumber":t=Number;break;case"ZodBoolean":t=Boolean;break;case"ZodDate":t=Date;break;case"ZodObject":break;case"ZodUnion":t={};break;default:throw new Error(`Unsupported type: ${e}`)}return y(n.definition)&&(t=f(n.definition)),n.defaultValue?{type:t,default:n.defaultValue}:t}function g(e){let o=e,n=!1,t;for(;"innerType"in o._def;)"defaultValue"in o._def&&(t=o._def.defaultValue()),o=o._def.innerType;return{definition:o,optional:n,defaultValue:t}}0&&(module.exports={createSchema});
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { z, ZodObject, ZodRawShape } from \"zod\";\nimport * as Mongoose from \"mongoose\";\nimport { SchemaDefinition } from \"mongoose\";\nimport { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName: string,\n connection: Mongoose.Connection,\n): { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName?: string,\n connection?: Mongoose.Connection,\n): Mongoose.Schema | { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> } {\n const convertedShape: Partial<SchemaDefinition> = {};\n for (const key in zodObject.shape) {\n const zodField = zodObject.shape[key];\n convertedShape[key] = convertField(key, zodField);\n }\n const schema = new Mongoose.Schema(convertedShape);\n if (!connection || !modelName) return schema;\n return { schema, model: connection.model<z.infer<typeof zodObject>>(modelName, schema) };\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n return definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n const unwrappedData = unwrapType(zodField);\n let coreType;\n switch (unwrappedData.definition._def.typeName) {\n case \"ZodString\":\n coreType = String;\n break;\n case \"ZodNumber\":\n coreType = Number;\n break;\n case \"ZodBoolean\":\n coreType = Boolean;\n break;\n case \"ZodDate\":\n coreType = Date;\n break;\n case \"ZodObject\":\n break;\n case \"ZodUnion\":\n coreType = {};\n break;\n default:\n throw new Error(`Unsupported type: ${type}`);\n }\n if (isZodObject(unwrappedData.definition)) {\n coreType = createSchema(unwrappedData.definition);\n }\n\n if (!unwrappedData.defaultValue) {\n return coreType;\n }\n return {\n type: coreType,\n default: unwrappedData.defaultValue,\n };\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { definition: SupportedType; optional: boolean; defaultValue?: unknown } {\n let definition = data;\n const optional = false;\n let defaultValue = undefined;\n while (\"innerType\" in definition._def) {\n if (\"defaultValue\" in definition._def) {\n defaultValue = definition._def.defaultValue();\n }\n definition = definition._def.innerType;\n }\n return { definition, optional, defaultValue };\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAA0B,yBAkBnB,SAASF,EACZG,EACAC,EACAC,EAC+F,CAC/F,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAC/B,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACpD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,OAAAA,EAAQ,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,CAAE,CAC3F,CAQA,SAASC,EAAYC,EAAiE,CAClF,OAAOA,EAAW,KAAK,WAAa,WACxC,CASA,SAASH,EAAoCI,EAAcL,EAAuC,CAC9F,IAAMM,EAAgBC,EAAWP,CAAQ,EACrCQ,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC5C,IAAK,YACDE,EAAW,OACX,MACJ,IAAK,YACDA,EAAW,OACX,MACJ,IAAK,aACDA,EAAW,QACX,MACJ,IAAK,UACDA,EAAW,KACX,MACJ,IAAK,YACD,MACJ,IAAK,WACDA,EAAW,CAAC,EACZ,MACJ,QACI,MAAM,IAAI,MAAM,qBAAqBH,CAAI,EAAE,CACnD,CAKA,OAJIF,EAAYG,EAAc,UAAU,IACpCE,EAAWhB,EAAac,EAAc,UAAU,GAG/CA,EAAc,aAGZ,CACH,KAAME,EACN,QAASF,EAAc,YAC3B,EALWE,CAMf,CAQA,SAASD,EAAWE,EAA+F,CAC/G,IAAIL,EAAaK,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeP,EAAW,MACzB,iBAAkBA,EAAW,OAC7BO,EAAeP,EAAW,KAAK,aAAa,GAEhDA,EAAaA,EAAW,KAAK,UAEjC,MAAO,CAAE,WAAAA,EAAY,SAAAM,EAAU,aAAAC,CAAa,CAChD","names":["src_exports","__export","createSchema","__toCommonJS","Mongoose","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","isZodObject","definition","type","unwrappedData","unwrapType","coreType","data","optional","defaultValue"]}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import*as i from"mongoose";function c(t,o,n){let e={};for(let d in t.shape){let r=t.shape[d];e[d]=p(d,r)}let a=new i.Schema(e);return!n||!o?a:{schema:a,model:n.model(o,a)}}function f(t){return t._def.typeName==="ZodObject"}function p(t,o){let n=s(o),e;switch(n.definition._def.typeName){case"ZodString":e=String;break;case"ZodNumber":e=Number;break;case"ZodBoolean":e=Boolean;break;case"ZodDate":e=Date;break;case"ZodObject":break;case"ZodUnion":e={};break;default:throw new Error(`Unsupported type: ${t}`)}return f(n.definition)&&(e=c(n.definition)),n.defaultValue?{type:e,default:n.defaultValue}:e}function s(t){let o=t,n=!1,e;for(;"innerType"in o._def;)"defaultValue"in o._def&&(e=o._def.defaultValue()),o=o._def.innerType;return{definition:o,optional:n,defaultValue:e}}export{c as createSchema};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { z, ZodObject, ZodRawShape } from \"zod\";\nimport * as Mongoose from \"mongoose\";\nimport { SchemaDefinition } from \"mongoose\";\nimport { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName: string,\n connection: Mongoose.Connection,\n): { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName?: string,\n connection?: Mongoose.Connection,\n): Mongoose.Schema | { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> } {\n const convertedShape: Partial<SchemaDefinition> = {};\n for (const key in zodObject.shape) {\n const zodField = zodObject.shape[key];\n convertedShape[key] = convertField(key, zodField);\n }\n const schema = new Mongoose.Schema(convertedShape);\n if (!connection || !modelName) return schema;\n return { schema, model: connection.model<z.infer<typeof zodObject>>(modelName, schema) };\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n return definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n const unwrappedData = unwrapType(zodField);\n let coreType;\n switch (unwrappedData.definition._def.typeName) {\n case \"ZodString\":\n coreType = String;\n break;\n case \"ZodNumber\":\n coreType = Number;\n break;\n case \"ZodBoolean\":\n coreType = Boolean;\n break;\n case \"ZodDate\":\n coreType = Date;\n break;\n case \"ZodObject\":\n break;\n case \"ZodUnion\":\n coreType = {};\n break;\n default:\n throw new Error(`Unsupported type: ${type}`);\n }\n if (isZodObject(unwrappedData.definition)) {\n coreType = createSchema(unwrappedData.definition);\n }\n\n if (!unwrappedData.defaultValue) {\n return coreType;\n }\n return {\n type: coreType,\n default: unwrappedData.defaultValue,\n };\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { definition: SupportedType; optional: boolean; defaultValue?: unknown } {\n let definition = data;\n const optional = false;\n let defaultValue = undefined;\n while (\"innerType\" in definition._def) {\n if (\"defaultValue\" in definition._def) {\n defaultValue = definition._def.defaultValue();\n }\n definition = definition._def.innerType;\n }\n return { definition, optional, defaultValue };\n}\n"],"mappings":"AACA,UAAYA,MAAc,WAkBnB,SAASC,EACZC,EACAC,EACAC,EAC+F,CAC/F,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAC/B,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACpD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,OAAAA,EAAQ,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,CAAE,CAC3F,CAQA,SAASC,EAAYC,EAAiE,CAClF,OAAOA,EAAW,KAAK,WAAa,WACxC,CASA,SAASH,EAAoCI,EAAcL,EAAuC,CAC9F,IAAMM,EAAgBC,EAAWP,CAAQ,EACrCQ,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC5C,IAAK,YACDE,EAAW,OACX,MACJ,IAAK,YACDA,EAAW,OACX,MACJ,IAAK,aACDA,EAAW,QACX,MACJ,IAAK,UACDA,EAAW,KACX,MACJ,IAAK,YACD,MACJ,IAAK,WACDA,EAAW,CAAC,EACZ,MACJ,QACI,MAAM,IAAI,MAAM,qBAAqBH,CAAI,EAAE,CACnD,CAKA,OAJIF,EAAYG,EAAc,UAAU,IACpCE,EAAWd,EAAaY,EAAc,UAAU,GAG/CA,EAAc,aAGZ,CACH,KAAME,EACN,QAASF,EAAc,YAC3B,EALWE,CAMf,CAQA,SAASD,EAAWE,EAA+F,CAC/G,IAAIL,EAAaK,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeP,EAAW,MACzB,iBAAkBA,EAAW,OAC7BO,EAAeP,EAAW,KAAK,aAAa,GAEhDA,EAAaA,EAAW,KAAK,UAEjC,MAAO,CAAE,WAAAA,EAAY,SAAAM,EAAU,aAAAC,CAAa,CAChD","names":["Mongoose","createSchema","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","isZodObject","definition","type","unwrappedData","unwrapType","coreType","data","optional","defaultValue"]}
@@ -0,0 +1 @@
1
+ export { createSchema } from '../_tsup-dts-rollup';
@@ -0,0 +1 @@
1
+ export { createSchema } from '../_tsup-dts-rollup';
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@mirite/zod-to-mongoose",
3
+ "version": "0.0.1",
4
+ "description": "Package for creating mongoose schemas out of Zod schemas for type safety, and removing duplicate effort.",
5
+ "types": "dist/_tsup-dts-rollup.d.ts",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mirite/zod-to-mongoose.git"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "author": {
21
+ "name": "Jesse Conner",
22
+ "email": "me@jesseconner.ca",
23
+ "url": "https://jesseconner.ca"
24
+ },
25
+ "keywords": [
26
+ "zod",
27
+ "mongoose",
28
+ "schema",
29
+ "type",
30
+ "type-safe"
31
+ ],
32
+ "issues": "https://github.com/mirite/zod-to-mongoose/issues",
33
+ "license": "MIT",
34
+ "scripts": {
35
+ "build": "tsup",
36
+ "test": "jest --coverage",
37
+ "lint": "eslint . --fix --ignore-path .gitignore",
38
+ "format": "prettier --write . --ignore-path .gitignore",
39
+ "release": "yarn build && npm publish"
40
+ },
41
+ "devDependencies": {
42
+ "@types/eslint": "^8.56.2",
43
+ "@types/jest": "^29.5.12",
44
+ "@typescript-eslint/eslint-plugin": "^7.0.1",
45
+ "@typescript-eslint/parser": "^7.0.1",
46
+ "eslint": "^8.56.0",
47
+ "eslint-plugin-jsdoc": "^48.0.6",
48
+ "jest": "^29.7.0",
49
+ "prettier": "^3.2.5",
50
+ "prettier-plugin-jsdoc": "^1.3.0",
51
+ "ts-jest": "^29.1.2",
52
+ "tsup": "^8.0.2",
53
+ "typescript": "^5.3.3"
54
+ },
55
+ "packageManager": "yarn@4.1.0",
56
+ "dependencies": {
57
+ "@microsoft/api-extractor": "^7.40.1",
58
+ "mongoose": "^8.1.2",
59
+ "zod": "^3.22.4"
60
+ }
61
+ }
package/readme.md ADDED
@@ -0,0 +1,67 @@
1
+ # Zod to Mongoose
2
+
3
+ This is a package for generating Mongoose schemas from Zod schemas. The goal is to improve type safety and reduce the amount of code that needs to be written when working with Mongoose.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ yarn add @mirite/zod-to-mongoose
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ### Basic
14
+
15
+ Passing in a Zod schema will return a Mongoose schema.
16
+ ```typescript
17
+ import { createSchema } from "@mirite/zod-to-mongoose";
18
+
19
+ const schema = createSchema(
20
+ z.object({
21
+ name: z.string().optional().default("Bob"),
22
+ age: z.number().default(3).optional(),
23
+ isHappy: z.boolean().optional(),
24
+ birthday: z.date().default(new Date()),
25
+ }),
26
+ );
27
+
28
+ const model = mongoose.model("modelName", schema);
29
+ const result = await model.create({
30
+ isHappy: true,
31
+ birthday: new Date("1980-01-01"),
32
+ });
33
+ ````
34
+
35
+ ### Advanced
36
+ If you pass a connection, the model will be created, 4registered with the connection, and returned for use.
37
+ ```typescript
38
+ import { createSchema } from "@mirite/zod-to-mongoose";
39
+
40
+
41
+ const model = createSchema(
42
+ z.object({
43
+ name: z.string().optional().default("Bob"),
44
+ age: z.number().default(3).optional(),
45
+ isHappy: z.boolean().optional(),
46
+ birthday: z.date().default(new Date()),
47
+ }),
48
+ "modelName", // The unique name to give the model
49
+ connection, // Mongoose connection
50
+ );
51
+
52
+ const result = await model.create({
53
+ isHappy: true,
54
+ birthday: new Date("1980-01-01"),
55
+ });
56
+ ```
57
+
58
+ ### Caveats
59
+ Only a subset of Zod types are supported. The following types are supported:
60
+ - `z.string()`
61
+ - `z.number()`
62
+ - `z.boolean()`
63
+ - `z.date()`
64
+ - `z.object()` (Nested objects are supported)
65
+ - `z.union()` (Type safety is not guaranteed)
66
+
67
+ Additionally, no additional validation is performed on the Mongoose schema.