Skip to content

Getting Started

Installation

1. Configure GitHub Packages

Create or update .npmrc in your project root:

ini
@codician-team:registry=https://npm.pkg.github.com
//npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}

You'll need a GitHub token with read:packages scope. Set it as an environment variable or replace ${GITHUB_TOKEN} with your token.

2. Install the package

bash
npm install @codician-team/monch
bash
yarn add @codician-team/monch
bash
pnpm add @codician-team/monch
bash
bun add @codician-team/monch

Quick Start

1. Set Environment Variable

bash
# .env
MONGODB_URI=mongodb://localhost:27017/myapp

2. Define a Collection

typescript
import { collection, field } from '@codician-team/monch';

export const Users = collection({
  name: 'users',
  schema: {
    _id: field.id(),
    name: field.string().min(1),
    email: field.email(),
    role: field.enum(['user', 'admin']).default('user'),
  },
  timestamps: true,  // Adds createdAt, updatedAt
});

3. Use It

typescript
// Insert (automatically validated)
const user = await Users.insertOne({
  name: 'Alice',
  email: 'alice@example.com',
});
// user: { _id: ObjectId, name: 'Alice', email: '...', role: 'user', createdAt: Date, updatedAt: Date }

// Query
const admins = await Users.find({ role: 'admin' }).toArray();

// Update (partial validation on $set fields)
await Users.updateOne(
  { _id: user._id },
  { $set: { role: 'admin' } }
);

// Serialize for JSON/Next.js
const plain = user.serialize();
// { _id: '507f1f77...', name: 'Alice', ... }

How It Works

Auto-Connection

Monch automatically connects to MongoDB on first operation. No setup code needed:

typescript
// First call triggers connection
const user = await Users.findOne({ email: 'alice@example.com' });

The connection is cached and reused for all subsequent operations.

Environment Variables

Monch checks these environment variables in order:

  1. MONGODB_URI - Primary connection string
  2. MONGO_URL - Common alternative
  3. DATABASE_URL - Used only if it's a MongoDB URI

For the database name:

  1. Explicit database config option
  2. Database in URI path (e.g., mongodb://localhost:27017/mydb)
  3. MONGODB_DATABASE or MONGO_DATABASE environment variable

Validation Flow

When you insert a document:

Input → beforeValidate hook → Zod validation → afterValidate hook →
        timestamps applied → beforeInsert hook → MongoDB insert → afterInsert hook

When you update:

Update → Partial validation of $set fields → timestamps updated → MongoDB update

Project Structure

A typical project structure with Monch:

src/
├── lib/
│   └── models/
│       ├── index.ts      # Re-export all collections
│       ├── user.model.ts
│       ├── post.model.ts
│       └── comment.model.ts
├── app/
│   ├── actions/
│   │   └── user.actions.ts  # Server actions using collections
│   └── api/
│       └── users/
│           └── route.ts     # API routes using collections

Example Model File

typescript
// src/lib/models/user.model.ts
import { collection, field, type ModelOf, type SerializedOf } from '@codician-team/monch';

export const Users = collection({
  name: 'users',
  schema: {
    _id: field.id(),
    name: field.string().min(1).max(100),
    email: field.email(),
    role: field.enum(['user', 'admin', 'moderator']).default('user'),
    profile: field.object({
      bio: field.string().max(500).optional(),
      avatar: field.url().optional(),
    }).optional(),
  },
  timestamps: true,
  indexes: [
    { key: { email: 1 }, unique: true },
    { key: { role: 1 } },
  ],
});

// Export types for use in components
export type User = ModelOf<typeof Users>;
export type SerializedUser = SerializedOf<typeof Users>;

Example Index File

typescript
// src/lib/models/index.ts
export { Users, type User, type SerializedUser } from './user.model';
export { Posts, type Post, type SerializedPost } from './post.model';
export { Comments, type Comment, type SerializedComment } from './comment.model';

Next Steps

Released under the MIT License.