Skip to content

Changelog

All notable changes to Monch will be documented in this file.

[0.3.0] - 2026-01-21

Breaking Changes

Removed methods and statics Options

The methods and statics configuration options have been removed from collections. This simplifies the codebase and aligns with modern TypeScript patterns favoring thin data models with external helper functions.

Before (removed):

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(),
  },
});

// Usage
const user = await Users.findOne({ _id: id });
user.fullName();           // Instance method
await Users.findAdmins();  // Static method

After (use helper functions):

typescript
const Users = collection({
  name: 'users',
  schema: { /* ... */ },
});

// Helper functions (preferred pattern)
export const UserHelpers = {
  fullName: (user: User) => `${user.firstName} ${user.lastName}`,
  isAdmin: (user: User) => user.role === 'admin',
  findByEmail: (email: string) => Users.findOne({ email }),
  findAdmins: () => Users.find({ role: 'admin' }).toArray(),
};

// Usage
const user = await Users.findOne({ _id: id });
UserHelpers.fullName(user);     // External helper
await UserHelpers.findAdmins(); // External helper

Benefits:

  • Type generics reduced from 4-5 to 2, simplifying type definitions
  • No per-document Object.defineProperty overhead for user methods
  • Better tree-shaking potential for helper functions
  • Simpler mental model - collections are pure data accessors
  • Helper functions are easier to test in isolation

Preserved: serialize() and toJSON() methods are still attached to documents for API/serialization use.

Removed Type Exports

The following type exports have been removed:

  • Methods<T> - no longer needed
  • Statics<T, I, M> - no longer needed
  • WithMethods<T, M> - no longer needed

Simplified Generic Parameters

Collection types now use fewer generics:

  • Collection<T, I, S> (was Collection<T, I, M, ST, S>)
  • CollectionInstance<T, I> (was CollectionInstance<T, I, M, ST>)
  • CollectionConfig<S, TS> (was CollectionConfig<S, TS, M, ST>)
  • Cursor<T> (was Cursor<T, M>)
  • MonchDocument<T> (was MonchDocument<T, M>)

Documentation

  • Removed /guide/methods and /guide/statics documentation pages
  • Updated e-commerce example to use external helper functions pattern
  • Updated API documentation to reflect simplified config options

[0.2.1] - 2026-01-21

Bug Fixes

  • Fixed circular reference causing stack overflow in serialization
  • Fixed BigInt values not being JSON.stringify compatible (now returns string)
  • Fixed invalid Date objects causing issues (now returns null)
  • Fixed Money.min() and Money.max() not validating currency consistency
  • Fixed Money.split() accepting non-integer parts
  • Fixed race condition in replaceOne with upsert
  • Fixed race condition in findOneAndReplace with upsert
  • Fixed bulkWrite missing createdAt for upsert operations
  • Fixed disconnectAll not waiting for in-progress connections
  • Fixed async iterator not cleaning up cursor on early break
  • Fixed pagination returning pages: 1 for empty collections (now returns 0)

Improvements

  • Added MonchHookError class for hook-related errors (separate from validation errors)
  • Added cause property to MonchConnectionError for better error chaining
  • Added input validation for cursor skip() and limit() methods
  • Added cursor count() method
  • Added cursor hasNext() method
  • Added consistent debug logging across all collection methods

New Tests

  • Added serialization edge case tests (circular refs, BigInt, invalid dates)
  • Added Money edge case tests (currency validation, split validation)
  • Added pagination edge case tests

[0.2.0] - 2026-01-21

Breaking Changes

Index Syntax Changed to MongoDB Native Format

The index definition syntax has been changed from a mixed format to MongoDB's native format with explicit key property:

typescript
// Before (mixed concerns - fields and options at same level)
indexes: [
  { email: 1, unique: true },
  { firstName: 1, lastName: 1 },
]

// After (clean separation - MongoDB native format)
indexes: [
  { key: { email: 1 }, unique: true },
  { key: { firstName: 1, lastName: 1 } },
]

Migration: Update all index definitions to use { key: { ...fields }, ...options } format.

ConnectionConfig Now Uses Discriminated Union

Connection configuration now enforces mutual exclusivity between connection strategies:

typescript
// Only ONE of these can be provided:
{ uri: string; database?: string }           // URI-based
{ client: MongoClient; database: string }    // Existing client
{ db: Db }                                   // Direct Db instance

CursorType Renamed to CursorInterface

The type export CursorType has been renamed to CursorInterface for clarity:

typescript
// Before
import type { CursorType } from '@codician-team/monch';

// After
import type { CursorInterface } from '@codician-team/monch';

Improvements

Type Safety Enhancements

  • MonchFilter: Changed from Record<string, any> to Record<string, unknown> for better type safety
  • findById: Parameter type changed from any to ObjectId | string
  • distinct: Now returns properly typed T[K][] instead of any[]
  • beforeValidate hook: Changed from any to unknown for better type safety

Index Type Improvements

  • Added support for partialFilterExpression option
  • Added support for collation option
  • Renamed indexName to name to match MongoDB conventions
  • Simplified type definition (no longer generic)

Code Quality

  • Removed duplicate CollectionConfig interface from collection.ts (now imports from types.ts)
  • Cleaner separation of concerns in index definitions

Documentation Fixes

Type Documentation

  • Fixed MoneyValue type: amount is Decimal128 (not number), removed incorrect formatted property
  • Fixed MoneyOptions to show correct properties: currency, min, max, allowNegative

Schema Documentation

  • Fixed $schema documentation: clarified it returns raw schema object, not ZodObject
  • Added example showing how to wrap with z.object() for manual validation

Validation Documentation

  • Added prominent danger warning about validation bypass with $inc, $push, $unset, etc.
  • Included concrete examples showing potential data integrity issues
  • Added mitigation strategies

CRUD Documentation

  • Clarified that updateOne returns the document (not MongoDB's UpdateResult)
  • Added info about accessing raw MongoDB methods if needed

Querying Documentation

  • Removed incorrect "more efficient" claim about cursor .serialize()

Hooks Documentation

  • Expanded explanation of WHY certain operations don't trigger hooks (atomicity, performance)
  • Clarified that only updateOne triggers update hooks

Pagination Documentation

  • Changed info box to warning about silent 100-item limit cap
  • Added example showing how to verify actual limit applied

Serialization Documentation

  • Added warning about MonchArray losing .serialize() after filter(), map(), slice()
  • Added example showing how to use serializeArray() helper

Example Fixes

  • Fixed transaction example: added missing { session } to reads inside transaction
  • Fixed basic-crud example: added required settings: {} to insert examples

Internal Changes

  • All 471 tests pass
  • Index-related tests updated to use new syntax
  • Type tests updated for new Index interface

Released under the MIT License.