Thin MongoDB ODM built for Standard Schema
mongodb
zod
deno
1import { z } from "@zod/zod";
2import { ObjectId } from "mongodb";
3import {
4 connect,
5 disconnect,
6 type InferModel,
7 type Input,
8 Model,
9} from "../mod.ts";
10
11// 1. Define your schema using Zod
12const userSchema = z.object({
13 name: z.string(),
14 email: z.email(),
15 age: z.number().int().positive().optional(),
16 createdAt: z.date().default(() => new Date()),
17});
18
19// Infer the TypeScript type from the Zod schema
20type User = InferModel<typeof userSchema>;
21type UserInsert = Input<typeof userSchema>;
22
23async function runExample() {
24 try {
25 // 3. Connect to MongoDB
26 await connect("mongodb://localhost:27017", "nozzle_example");
27 console.log("Connected to MongoDB");
28
29 // 2. Create a Model for your collection
30 const UserModel = new Model("users", userSchema);
31
32 // Clean up previous data
33 await UserModel.delete({});
34
35 // 4. Insert a new document
36 const newUser: UserInsert = {
37 name: "Alice Smith",
38 email: "alice@example.com",
39 age: 30,
40 };
41 const insertResult = await UserModel.insertOne(newUser);
42 console.log("Inserted user:", insertResult.insertedId);
43
44 // 5. Find documents
45 const users = await UserModel.find({ name: "Alice Smith" });
46 console.log("Found users:", users);
47
48 // 6. Find one document
49 const foundUser = await UserModel.findOne({
50 _id: new ObjectId(insertResult.insertedId),
51 });
52 console.log("Found one user:", foundUser);
53
54 // 7. Update a document
55 const updateResult = await UserModel.update(
56 { _id: new ObjectId(insertResult.insertedId) },
57 { age: 31 },
58 );
59 console.log("Updated user count:", updateResult.modifiedCount);
60
61 const updatedUser = await UserModel.findOne({
62 _id: new ObjectId(insertResult.insertedId),
63 });
64 console.log("Updated user data:", updatedUser);
65
66 // 8. Delete documents
67 const deleteResult = await UserModel.delete({ name: "Alice Smith" });
68 console.log("Deleted user count:", deleteResult.deletedCount);
69 } catch (error) {
70 console.error("Error during example run:", error);
71 } finally {
72 // 9. Disconnect from MongoDB
73 await disconnect();
74 console.log("Disconnected from MongoDB");
75 }
76}
77
78// Only run the example if this is the main module
79if (import.meta.main) {
80 runExample();
81}