Skip to main content

Collection Methods

All CRUD operations go through the mongo.from(Collection) API.

Setup

import { MongoDataSource, defineCollection, prop } from "hysteria-orm";

const mongo = new MongoDataSource({
url: "mongodb://root:root@localhost:27017",
});
await mongo.connect();

const User = defineCollection("users", {
properties: {
name: prop.string(),
email: prop.string(),
},
});

CRUD Methods

find

Fetch multiple documents.

const users = await mongo
.from(User)
.find({ where: { email: "test@example.com" } });

findOne

Fetch a single document.

const user = await mongo
.from(User)
.findOne({ where: { email: "test@example.com" } });

findOneOrFail

Fetch a single document or throw if not found.

const user = await mongo
.from(User)
.findOneOrFail({ where: { email: "test@example.com" } });

insert

Insert a new document.

const user = await mongo
.from(User)
.insert({ name: "Test", email: "test@example.com" });

insertMany

Insert multiple documents.

const users = await mongo.from(User).insertMany([
{ name: "Test 1", email: "test1@example.com" },
{ name: "Test 2", email: "test2@example.com" },
]);

updateRecord

Update a document by id.

user.name = "Updated";
const updated = await mongo.from(User).updateRecord(user);

deleteRecord

Delete a document by id.

await mongo.from(User).deleteRecord(user);

Raw Collection Access

Access the underlying MongoDB driver collection directly:

const rawCollection = mongo.getCurrentConnection().db().collection("users");

Untyped Raw Queries

Use mongo.query() for untyped queries against any collection:

const results = await mongo.query("users");

Best Practices

  • Always use mongo.from(Collection) for database operations.
  • Use findOneOrFail for required lookups.

Next: MongoDB Query Builder