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