Thin MongoDB ODM built for Standard Schema
mongodb zod deno

modeldef

knotbin.com e0183687 80092f8a

verified
Changed files
+41 -5
model
+15 -3
model/index.ts
··· 24 24 } from "mongodb"; 25 25 import type { ObjectId } from "mongodb"; 26 26 import { getDb } from "../client/connection.ts"; 27 - import type { Schema, Infer, Input } from "../types.ts"; 27 + import type { Schema, Infer, Input, Indexes, ModelDef } from "../types.ts"; 28 28 import * as core from "./core.ts"; 29 29 import * as indexes from "./indexes.ts"; 30 30 import * as pagination from "./pagination.ts"; ··· 49 49 export class Model<T extends Schema> { 50 50 private collection: Collection<Infer<T>>; 51 51 private schema: T; 52 + private indexes?: Indexes; 52 53 53 - constructor(collectionName: string, schema: T) { 54 + constructor(collectionName: string, definition: ModelDef<T> | T) { 55 + if ("schema" in definition) { 56 + this.schema = definition.schema; 57 + this.indexes = definition.indexes; 58 + } else { 59 + this.schema = definition as T; 60 + } 54 61 this.collection = getDb().collection<Infer<T>>(collectionName); 55 - this.schema = schema; 62 + 63 + // Automatically create indexes if they were provided 64 + if (this.indexes && this.indexes.length > 0) { 65 + // Fire and forget - indexes will be created asynchronously 66 + indexes.syncIndexes(this.collection, this.indexes) 67 + } 56 68 } 57 69 58 70 // ============================================================================
+26 -2
types.ts
··· 1 1 import type { z } from "@zod/zod"; 2 - import type { Document, ObjectId } from "mongodb"; 2 + import type { Document, ObjectId, IndexDescription } from "mongodb"; 3 3 4 4 /** 5 5 * Type alias for Zod schema objects ··· 22 22 /** 23 23 * Infer the input type for a Zod schema (handles defaults) 24 24 */ 25 - export type Input<T extends Schema> = z.input<T>; 25 + export type Input<T extends Schema> = z.input<T>; 26 + 27 + /** 28 + * Type for indexes that can be passed to the Model constructor 29 + */ 30 + export type Indexes = IndexDescription[]; 31 + 32 + /** 33 + * Complete definition of a model, including schema and indexes 34 + * 35 + * @example 36 + * ```ts 37 + * const userDef: ModelDef<typeof userSchema> = { 38 + * schema: userSchema, 39 + * indexes: [ 40 + * { key: { email: 1 }, unique: true }, 41 + * { key: { name: 1 } } 42 + * ] 43 + * }; 44 + * ``` 45 + */ 46 + export type ModelDef<T extends Schema> = { 47 + schema: T; 48 + indexes?: Indexes; 49 + };