# esix

> A really slick ORM for MongoDB.

Latest version **5.7.0** (published 2026-09-09) · MIT license · 0 weekly downloads

## Install

```sh
npm install esix
pnpm add esix
yarn add esix
bun add esix
```

## Health

**Score 75/100 (B)** — status: active.

Positive: has types; esm support; no vulnerabilities; has provenance; recently updated; high maintenance score; high quality score.

Warnings: low downloads.

## Facts

| | |
|---|---|
| Version | 5.7.0 |
| Published | 2026-09-09 |
| First published | 2020-07-12 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >= 20 |
| Dependencies | 4 |
| Unpacked size | 187.6 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Provenance | attested (GitHub Actions) |
| GitHub stars | 5 |
| Author | Christoffer Artmann |
| Maintainers | artmann |
| Keywords | mongodb, orm, typescript, esix, blazing-fast |

## Links

- npm: https://www.npmjs.com/package/esix
- Repository: https://github.com/Artmann/esix
- Homepage: https://esix.netlify.app/
- Issues: https://github.com/Artmann/esix/issues
- npm.io page: https://npm.io/package/esix

## Dependencies (4)

- [pluralize](https://npm.io/package/pluralize.md) ^8.0.0
- [percentile](https://npm.io/package/percentile.md) ^1.6.0
- [change-case](https://npm.io/package/change-case.md) ^5.4.4
- [reflect-metadata](https://npm.io/package/reflect-metadata.md) ^0.2.2

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 5.7.0 (latest) — 2026-09-09
- 5.6.0 — 2026-07-17
- 5.5.1 — 2026-07-16
- 5.4.0 — 2025-07-04
- 5.3.0 — 2025-04-22
- 5.2.0 — 2025-04-16
- 5.1.1 — 2025-04-01
- 5.1.0 — 2025-04-01
- 5.0.0 — 2025-03-27
- 4.0.0 — 2025-03-27
- 3.2.1 — 2022-04-11
- 3.2.0 — 2022-04-06
- 3.1.0 — 2022-04-05
- 3.0.2 — 2021-02-04
- 3.0.1 — 2020-12-28
- … 15 more at https://npm.io/package/esix/versions

## README

<p align="center">
  <img alt="Esix" src="./logo.png" width="240px"/>
</p>

<h1 align="center">Esix: Type-safe MongoDB ORM with zero configuration</h1>

<p align="center">
  <a href="https://www.npmjs.com/package/esix"><img src="https://img.shields.io/npm/v/esix.svg" alt="npm version"></a>
  <a href="https://www.npmjs.com/package/esix"><img src="https://img.shields.io/npm/dm/esix.svg" alt="npm downloads"></a>
  <a href="https://github.com/Artmann/esix/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Artmann/esix.svg" alt="License"></a>
  <a href="https://github.com/Artmann/esix/actions"><img src="https://img.shields.io/github/actions/workflow/status/Artmann/esix/build.yml" alt="Build Status"></a>
  <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-Ready-blue.svg" alt="TypeScript"></a>
  <a href="https://deepwiki.com/Artmann/esix"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
</p>

---

Working with MongoDB in TypeScript usually means choosing between simplicity and
type safety. Native drivers require verbose, untyped queries, while most ORMs
demand extensive configuration and boilerplate.

Esix brings the elegance of ActiveRecord and Eloquent to MongoDB with full
TypeScript support. Define your models as simple TypeScript classes, and Esix
automatically handles database operations and type inference through sensible
conventions.

**No configuration files, no setup overhead**—just MongoDB development that
feels as natural as working with any TypeScript object while maintaining the
flexibility that makes MongoDB powerful.

## Features

- **Zero Configuration** - No decorators, no config files, just TypeScript
  classes
- **Full Type Safety** - Leverages TypeScript's type system for compile-time
  safety
- **Eloquent-Style API** - Familiar, intuitive syntax inspired by Laravel and
  ActiveRecord
- **Automatic Connection** - Connects to MongoDB automatically when needed
- **Rich Query Builder** - Fluent API with comparison operators, sorting,
  pagination, and more
- **Aggregation Support** - Built-in methods for common aggregations (count,
  sum, average, etc.)
- **Relationships** - Simple, type-safe relationship definitions
- **NoSQL Injection Protection** - Automatic input sanitization

## Installation

```bash
npm install esix mongodb
# or
yarn add esix mongodb
```

## Quick Start

Set your MongoDB connection string (Esix automatically connects when needed):

```bash
export DB_URL=mongodb://localhost:27017/myapp
```

### Define Models

Create TypeScript classes that extend `BaseModel`:

```ts
import { BaseModel } from 'esix'

class User extends BaseModel {
  public name = ''
  public email = ''
  public age = 0
  public isActive = true
}

class Post extends BaseModel {
  public title = ''
  public content = ''
  public authorId = ''
  public tags: string[] = []
  public publishedAt: Date | null = null
}
```

### Basic Operations

```ts
// Create
const user = await User.create({
  name: 'John Smith',
  email: 'john@example.com',
  age: 30
})

// Find by ID
const foundUser = await User.find(user.id)

// Find all
const allUsers = await User.all()

// Update
user.age = 31
await user.save()

// Delete
await user.delete()
```

### Querying

Esix provides a powerful, fluent query builder with full type safety:

```ts
// Find by field
const activeUsers = await User.where('isActive', true).get()

// Comparison operators
const adults = await User.where('age', '>', 18).get()
const seniors = await User.where('age', '>=', 65).get()
const youngUsers = await User.where('age', '<', 30).get()
const affordableItems = await Product.where('price', '<=', 50).get()
const nonBannedUsers = await User.where('status', '!=', 'banned').get()

// Multiple conditions
const youngActiveUsers = await User.where('isActive', true)
  .where('age', '<', 25)
  .get()

// Range queries
const workingAge = await User.where('age', '>=', 18)
  .where('age', '<=', 65)
  .get()

// Find one
const admin = await User.where('email', 'admin@example.com').first()

// Specific field search
const john = await User.findBy('email', 'john@example.com')

// Array queries
const bloggers = await User.whereIn('id', ['user1', 'user2', 'user3']).get()
const nonAdmins = await User.whereNotIn('role', ['admin', 'moderator']).get()
```

### Advanced Queries

```ts
// Pagination — built-in helper that returns data + metadata
const { data, total, lastPage } = await Post.paginate(1, 20)

// Manual pagination with skip/limit
const page1 = await Post.limit(10).get()
const page2 = await Post.skip(10).limit(10).get()

// Sorting
const latestPosts = await Post.orderBy('createdAt', 'desc').get()
const popularPosts = await Post.orderBy('views', 'desc').limit(5).get()

// Extract specific field values
const titles = await Post.pluck('title')
const authors = await Post.pluck('authorId')

// Distinct values
const tags = await Post.where('published', true).distinct('tag')

// Full-text search (requires a text index on the collection)
const results = await Post.search('mongodb typescript').get()
```

### Updating Counts

Bump numeric fields without round-tripping through `.save()`:

```ts
await Post.where('id', postId).increment('views')
await User.where('isActive', true).increment('score', 5)
await Account.where('id', accountId).decrement('balance', 25)
```

### Aggregations

```ts
// Count documents
const userCount = await User.count()
const activeCount = await User.where('isActive', true).count()

// Sum values
const totalSales = await Order.sum('amount')

// Calculate averages
const avgAge = await User.average('age')

// Find min/max
const lowestPrice = await Product.min('price')
const highestScore = await Test.max('score')

// Percentiles
const p95ResponseTime = await ResponseTime.percentile('value', 95)

// Custom aggregations
const results = await User.aggregate([
  { $group: { _id: '$department', count: { $sum: 1 } } }
])
```

### First or Create

Find existing records or create new ones atomically:

```ts
// Find user by email, create if doesn't exist
const user = await User.firstOrCreate(
  { email: 'new@example.com' },
  { name: 'New User', age: 25 }
)

// Using only filter (attributes default to filter)
const settings = await Settings.firstOrCreate({
  userId: 'user123',
  theme: 'dark'
})
```

### Relationships

Define relationships between models with type safety. Esix ships with `hasMany`,
`hasOne`, and `belongsTo`:

```ts
class Author extends BaseModel {
  public name = ''

  // One author -> many posts
  posts() {
    return this.hasMany(Post)
  }

  // One author -> one profile
  profile() {
    return this.hasOne(Profile)
  }
}

class Post extends BaseModel {
  public title = ''
  public authorId = ''

  // Inverse: each post belongs to an author
  author() {
    return this.belongsTo(Author)
  }
}

// Usage
const author = await Author.find('author123')
const authorPosts = await author.posts().get()
const profile = await author.profile()

const post = await Post.find('post-1')
const writer = await post.author()
```

### Real-world Example

```ts
// Blog API endpoints
export async function getPosts(req: Request, res: Response) {
  const posts = await Post.where('publishedAt', '!=', null)
    .orderBy('publishedAt', 'desc')
    .limit(20)
    .get()

  res.json({ posts })
}

export async function createPost(req: Request, res: Response) {
  const post = await Post.create({
    title: req.body.title,
    content: req.body.content,
    authorId: req.user.id,
    tags: req.body.tags || []
  })

  res.json({ post })
}

export async function getOrCreateUser(req: Request, res: Response) {
  const user = await User.firstOrCreate(
    { email: req.body.email },
    { name: req.body.name, isActive: true }
  )

  res.json({ user, created: user.createdAt === user.updatedAt })
}
```

## Effect

Use `esix/effect` for lazy typed queries, Option lookups, connection Layers, and
Streams with Effect 3. Existing model classes work with both APIs. Start with
the [Effect Quickstart](https://www.esixorm.com/docs/effect-quickstart) or read
the [integration guide](https://www.esixorm.com/docs/effect).

## Configuration

Esix works with zero configuration but supports these environment variables:

- `DB_URL` - MongoDB connection string (required)
- `DB_DATABASE` - Database name (optional, extracted from URL if not provided)
- `DB_ADAPTER` - Set to `'mock'` for testing (optional)

## Documentation

For comprehensive documentation, visit <https://www.esixorm.com/>.

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for
development setup and guidelines.

## License

MIT © [Christoffer Artmann](https://github.com/Artmann)

---
_Source: https://npm.io/package/esix · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
