npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

esix

v5.6.0

Published

A really slick ORM for MongoDB.

Downloads

560

Readme


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

npm install esix mongodb
# or
yarn add esix mongodb

Quick Start

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

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

Define Models

Create TypeScript classes that extend BaseModel:

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

// Create
const user = await User.create({
  name: 'John Smith',
  email: '[email protected]',
  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:

// 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', '[email protected]').first()

// Specific field search
const john = await User.findBy('email', '[email protected]')

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

Advanced Queries

// 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():

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

Aggregations

// 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:

// Find user by email, create if doesn't exist
const user = await User.firstOrCreate(
  { email: '[email protected]' },
  { 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:

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

// 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 })
}

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 for development setup and guidelines.

License

MIT © Christoffer Artmann