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
···
} from "mongodb";
import type { ObjectId } from "mongodb";
import { getDb } from "../client/connection.ts";
-
import type { Schema, Infer, Input } from "../types.ts";
+
import type { Schema, Infer, Input, Indexes, ModelDef } from "../types.ts";
import * as core from "./core.ts";
import * as indexes from "./indexes.ts";
import * as pagination from "./pagination.ts";
···
export class Model<T extends Schema> {
private collection: Collection<Infer<T>>;
private schema: T;
+
private indexes?: Indexes;
-
constructor(collectionName: string, schema: T) {
+
constructor(collectionName: string, definition: ModelDef<T> | T) {
+
if ("schema" in definition) {
+
this.schema = definition.schema;
+
this.indexes = definition.indexes;
+
} else {
+
this.schema = definition as T;
+
}
this.collection = getDb().collection<Infer<T>>(collectionName);
-
this.schema = schema;
+
+
// Automatically create indexes if they were provided
+
if (this.indexes && this.indexes.length > 0) {
+
// Fire and forget - indexes will be created asynchronously
+
indexes.syncIndexes(this.collection, this.indexes)
+
}
}
// ============================================================================
+26 -2
types.ts
···
import type { z } from "@zod/zod";
-
import type { Document, ObjectId } from "mongodb";
+
import type { Document, ObjectId, IndexDescription } from "mongodb";
/**
* Type alias for Zod schema objects
···
/**
* Infer the input type for a Zod schema (handles defaults)
*/
-
export type Input<T extends Schema> = z.input<T>;
+
export type Input<T extends Schema> = z.input<T>;
+
+
/**
+
* Type for indexes that can be passed to the Model constructor
+
*/
+
export type Indexes = IndexDescription[];
+
+
/**
+
* Complete definition of a model, including schema and indexes
+
*
+
* @example
+
* ```ts
+
* const userDef: ModelDef<typeof userSchema> = {
+
* schema: userSchema,
+
* indexes: [
+
* { key: { email: 1 }, unique: true },
+
* { key: { name: 1 } }
+
* ]
+
* };
+
* ```
+
*/
+
export type ModelDef<T extends Schema> = {
+
schema: T;
+
indexes?: Indexes;
+
};