Model
Think of it as a class to query your collection with
A Mongster model is the typed entry point for one collection. It combines a collection name with a schema and exposes CRUD, aggregation, hooks, and index management.
import { , , } from "mongster";
const = .({
: .().(),
: .().(1),
}).();
const = ("users", );
const = .({
: .(),
: .().(() => new ()),
});
const = .("audit_logs", );
await .({ : false });
const = .();
const = .();Ways to create a model
model(name, schema)uses the default exportedmongsterclient.mongster.model(name, schema)is the same idea, but more explicit.client.model(name, schema)is for customMongsterClientinstances.
The shape of the API
- Create:
insertOne,insertMany,createOne,createMany - Read:
find,findOne,findById,count,estimatedCount,distinct - Update:
updateOne,updateMany,findOneAndUpdate,replaceOne,findOneAndReplace,upsertOne - Delete:
deleteOne,deleteMany,findOneAndDelete - Extra:
aggregate,aggregateRaw,bulkWrite,syncIndexes,pre,post
insert* vs create*
Use insertOne and insertMany when you want MongoDB's raw write result. Use createOne and createMany when you want the created documents back.
Common write operations
replaceOne and friends
replaceOne, findOneAndReplace, findOneAndUpdate, and findOneAndDelete all run through the schema and return a typed result.
import { } from "./models";
const = new ();
await .(
{ : },
{ : "Rewrite the docs", : false },
);
const = await .(
{ : },
{ : { : true } },
{ : true },
);
await .({ : }, { : true });[!NOTE]
findOneAndUpdate,findOneAndReplace, andfindOneAndDeleterequireincludeResultMetadata: trueinoptionsfor the typed return shape. The MongoDB driver enforces this for typed return values.
upsertOne
upsertOne(filter, doc) parses the document with the schema and routes the body into $set plus $setOnInsert: { _id }. Use it when you have a natural unique key and want a single round trip.
await .(
{ : "alice@example.com" },
{ : "alice@example.com", : "Alice" },
);bulkWrite
bulkWrite(operations, options) forwards an array of write operations to the driver. Mongster triggers syncIndexes() for the model before the call if it has not run yet, and fires the bulkWrite hook with the operations array.
await .([
{ : { : { : }, : { : { : true } } } },
{ : { : { : true } } },
]);For typed aggregations, see the Aggregation guide and the Aggregate API.
Transaction-scoped models
Inside mongster.transaction(), call ctx.use(Model) to get a transaction-scoped model with the same surface area and the session already injected.