Skip to content

Artmann/esix

Repository files navigation

Esix

Esix: Type-safe MongoDB ORM with zero configuration

npm version npm downloads License Build Status TypeScript

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.

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

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

// Multiple conditions
const youngActiveUsers = await User.where('isActive', true)
  .where('age', '<', 25)
  .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
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')

First or Create

Find existing records or create new ones:

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

class Author extends BaseModel {
  public name = ''

  // Get all posts by this author
  posts() {
    return this.hasMany(Post, 'authorId')
  }
}

// Usage
const author = await Author.find('author123')
const authorPosts = await author.posts().get()
const publishedPosts = await author
  .posts()
  .where('publishedAt', '!=', null)
  .get()

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://esix.netlify.app/.

About

A really slick ORM for MongoDB.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •