Skip to content

Migrate from the native driver

Before / after

typescript
// Before
import { MongoClient, ObjectId } from "mongodb";

const client = new MongoClient(uri);
await client.connect();
const col = client.db().collection("users");
await col.insertOne({ email: "a@b.com", role: "USER" });
const doc = await col.findOne({ email: "a@b.com" });
typescript
// After
import { createClient, defineSchema, s, ObjectId } from "mondel";

const userSchema = defineSchema("users", {
  fields: {
    email: s.string().required(),
    role: s.enum(["ADMIN", "USER"]).default("USER"),
  },
});

const schemas = [userSchema] as const;

const db = await createClient({ uri, schemas, validation: "strict" });
await db.users.create({ email: "a@b.com" });
const doc = await db.users.findOne({ email: "a@b.com" });

Mapping cheat sheet

DriverMondel
collection.insertOnecreate
insertManycreateMany
findOnefindOne
find().toArray()findMany
updateOneupdateOne (plain objects auto-$set)
deleteOnedeleteOne
aggregateaggregate
bulkWritebulkWrite
findOneAndUpdatefindOneAndUpdate
Anything elsegetCollection()

Filters stay the same

typescript
// Identical filter documents
{ age: { $gte: 18 }, status: { $in: ["A", "B"] } }

Incremental adoption

  1. Add schemas for hot collections only
  2. Keep using getCollection() for complex paths
  3. Turn validation: "loose" during migration, then "strict"
  4. Move index creation to npx mondel push

ObjectId

typescript
import { ObjectId } from "mondel";
// Prefer this over importing from a second mongodb/bson copy

Released under the MIT License. · llms.txt