Thin MongoDB ODM built for Standard Schema
mongodb
zod
deno
1import { z } from 'zod';
2import { Collection, InsertOneResult, UpdateResult, DeleteResult, Document, ObjectId, Filter } from 'mongodb';
3import { getDb } from './client';
4import { InsertType } from './schema';
5
6export class MongoModel<T extends z.ZodObject<any>> {
7 private collection: Collection<z.infer<T>>;
8 private schema: T;
9
10 constructor(collectionName: string, schema: T) {
11 this.collection = getDb().collection<z.infer<T>>(collectionName);
12 this.schema = schema;
13 }
14
15 async insertOne(data: InsertType<T>): Promise<InsertOneResult<z.infer<T>>> {
16 const validatedData = this.schema.parse(data);
17 return this.collection.insertOne(validatedData as any);
18 }
19
20 find(query: Filter<z.infer<T>>): Promise<(z.infer<T> & { _id: ObjectId })[]> {
21 return this.collection.find(query).toArray() as Promise<(z.infer<T> & { _id: ObjectId })[]>;
22 }
23
24 findOne(query: Filter<z.infer<T>>): Promise<(z.infer<T> & { _id: ObjectId }) | null> {
25 return this.collection.findOne(query) as Promise<(z.infer<T> & { _id: ObjectId }) | null>;
26 }
27
28 async update(query: Filter<z.infer<T>>, data: Partial<z.infer<T>>): Promise<UpdateResult> {
29 return this.collection.updateMany(query, { $set: data });
30 }
31
32 delete(query: Filter<z.infer<T>>): Promise<DeleteResult> {
33 return this.collection.deleteMany(query);
34 }
35}
36
37