collection()
Creates a Monch collection with Zod validation and MongoDB integration.
Signature
typescript
function collection<S, M, ST>(config: CollectionConfig<S, M, ST>): Collection<S, M, ST>Configuration
typescript
const Users = collection({
// Required
name: string, // MongoDB collection name
schema: Schema, // Zod schema object
// Connection (choose one or use auto-connect)
uri?: string, // MongoDB connection string
client?: MongoClient, // Existing MongoClient
db?: Db, // Existing Db instance
database?: string, // Database name
// Features
timestamps?: boolean, // Add createdAt/updatedAt (default: false)
indexes?: Index[], // Index definitions
createIndexes?: boolean, // Auto-create indexes (default: true)
// Extensibility
hooks?: Hooks<T>, // Lifecycle hooks
methods?: Methods<T>, // Instance methods
statics?: Statics<T, M>, // Static methods
});Collection Methods
Query Methods
| Method | Returns | Description |
|---|---|---|
find(filter?) | Cursor<T> | Find documents, returns chainable cursor |
findOne(filter) | Promise<Doc | null> | Find single document |
findById(id) | Promise<Doc | null> | Find by ObjectId (accepts string) |
count(filter?) | Promise<number> | Count matching documents |
estimatedDocumentCount() | Promise<number> | Fast count using metadata |
exists(filter) | Promise<boolean> | Check if any documents match |
distinct(key, filter?) | Promise<any[]> | Get distinct values |
Write Methods
| Method | Returns | Description |
|---|---|---|
insertOne(doc, opts?) | Promise<Doc> | Insert one (validated) |
insertMany(docs, opts?) | Promise<Doc[]> | Insert multiple (validated) |
updateOne(filter, update, opts?) | Promise<Doc | null> | Update one, return document |
updateMany(filter, update, opts?) | Promise<number> | Update multiple, return count |
replaceOne(filter, doc, opts?) | Promise<UpdateResult> | Replace document (validated) |
deleteOne(filter, opts?) | Promise<boolean> | Delete one, return success |
deleteMany(filter, opts?) | Promise<number> | Delete multiple, return count |
Atomic Methods
| Method | Returns | Description |
|---|---|---|
findOneAndUpdate(filter, update, opts?) | Promise<Doc | null> | Atomic find and update |
findOneAndDelete(filter, opts?) | Promise<Doc | null> | Atomic find and delete |
findOneAndReplace(filter, doc, opts?) | Promise<Doc | null> | Atomic find and replace |
Bulk & Aggregation
| Method | Returns | Description |
|---|---|---|
bulkWrite(operations, opts?) | Promise<BulkWriteResult> | Bulk operations |
aggregate(pipeline?, opts?) | AggregationCursor | Run aggregation |
Utility Methods
| Method | Returns | Description |
|---|---|---|
transaction(fn) | Promise<T> | Execute in transaction |
ensureIndexes() | Promise<string[]> | Create configured indexes |
Collection Properties
| Property | Type | Description |
|---|---|---|
$schema | ZodObject | Runtime Zod schema |
$model | type only | Document type |
$serialized | type only | Serialized type |
collection | Promise<MongoCollection> | Raw MongoDB collection |
client | Promise<MongoClient> | Raw MongoDB client |
Examples
Basic Collection
typescript
const Users = collection({
name: 'users',
schema: {
_id: field.id(),
name: field.string().min(1),
email: field.email(),
},
});With Timestamps and Indexes
typescript
const Posts = collection({
name: 'posts',
schema: {
_id: field.id(),
title: field.string(),
content: field.string(),
authorId: field.objectId(),
},
timestamps: true,
indexes: [
{ key: { authorId: 1, createdAt: -1 } },
{ key: { title: 'text', content: 'text' } },
],
});With Hooks
typescript
const Posts = collection({
name: 'posts',
schema: { /* ... */ },
hooks: {
beforeValidate: (doc) => ({
...doc,
slug: doc.title.toLowerCase().replace(/\s+/g, '-'),
}),
afterInsert: async (doc) => {
await notifySubscribers(doc);
},
},
});With Methods and Statics
typescript
const Users = collection({
name: 'users',
schema: { /* ... */ },
methods: {
fullName: (doc) => `${doc.firstName} ${doc.lastName}`,
isAdmin: (doc) => doc.role === 'admin',
},
statics: {
findByEmail: (col, email: string) => col.findOne({ email }),
findAdmins: (col) => col.find({ role: 'admin' }).toArray(),
},
});With Explicit Connection
typescript
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
const Users = collection({
name: 'users',
schema: { /* ... */ },
client,
database: 'myapp',
});