Thin MongoDB ODM built for Standard Schema
mongodb zod deno
1import { type Db, MongoClient } from "mongodb"; 2 3interface Connection { 4 client: MongoClient; 5 db: Db; 6} 7 8let connection: Connection | null = null; 9 10export async function connect( 11 uri: string, 12 dbName: string, 13): Promise<Connection> { 14 if (connection) { 15 return connection; 16 } 17 18 const client = new MongoClient(uri); 19 await client.connect(); 20 const db = client.db(dbName); 21 22 connection = { client, db }; 23 return connection; 24} 25 26export async function disconnect(): Promise<void> { 27 if (connection) { 28 await connection.client.close(); 29 connection = null; 30 } 31} 32 33export function getDb(): Db { 34 if (!connection) { 35 throw new Error("MongoDB not connected. Call connect() first."); 36 } 37 return connection.db; 38}