npm.io
0.0.4 • Published 6d ago

@eloquentjs/mongodb

Licence
MIT
Version
0.0.4
Deps
2
Size
16 kB
Vulns
0
Weekly
0
Stars
73

@eloquentjs/mongodb

MongoDB driver for EloquentJS. Use the same Eloquent API against MongoDB collections.

npm install @eloquentjs/core @eloquentjs/mongodb

Setup

import { connect } from '@eloquentjs/mongodb'
import { Model } from '@eloquentjs/core'

await connect({
  url:      process.env.MONGO_URL      ?? 'mongodb://localhost:27017',
  database: process.env.MONGO_DATABASE ?? 'myapp',
  // Optional auth
  username: process.env.MONGO_USERNAME,
  password: process.env.MONGO_PASSWORD,
})

class User extends Model {
  static table = 'users'   // maps to MongoDB collection name
}

await User.create({ name: 'Alice' })
await User.where('active', true).get()
await User.find('64a7f...')   // ObjectId string

MongoDB-Specific Features

// ObjectId handling — _id is automatically mapped to 'id'
const user = await User.find('64a7f3b2c1a2b3c4d5e6f7a8')
console.log(user.id)  // '64a7f3b2c1a2b3c4d5e6f7a8'

// Nested document queries
await User.where('address.city', 'New York').get()
await User.where('settings.theme', 'dark').get()

// Array contains
await User.where('tags', 'javascript').get()
await User.whereJsonContains('permissions', 'admin').get()

// Text search (requires text index on collection)
await User.whereRaw({ $text: { $search: 'Alice' } }).get()

// Geospatial (raw query)
await User.whereRaw({
  location: {
    $near: { $geometry: { type: 'Point', coordinates: [-73.9, 40.7] }, $maxDistance: 5000 }
  }
}).get()

Using with Multiple Connections

import { connect } from '@eloquentjs/mongodb'
import { connect as pgConnect } from '@eloquentjs/pgsql'

// Connect both drivers
await pgConnect({ host: 'localhost', database: 'app' })
const mongoConn = await connect({ url: 'mongodb://localhost', database: 'analytics' })

// Use MongoDB for specific models
class PageView extends Model {
  static connection = mongoConn
  static table      = 'page_views'
}

// Other models still use PostgreSQL
class User extends Model {
  static table = 'users'
}

Schema (Collections & Indexes)

MongoDB is schemaless, but you can manage indexes:

import { Schema } from '@eloquentjs/core'

await Schema.create('users', col => {
  col.index('email', { unique: true })
  col.index({ name: 'text', bio: 'text' })   // text index
  col.index({ location: '2dsphere' })         // geo index
  col.index(['tenant_id', 'created_at'])      // compound index
})

await Schema.dropIfExists('old_collection')
await Schema.hasTable('users')

Configuration Reference

Option Default Description
url mongodb://localhost:27017 MongoDB connection URL
database Database name (required)
username Auth username
password Auth password
authSource admin Auth database
tls false Enable TLS
replicaSet Replica set name
maxPoolSize 10 Max connection pool size

License

MIT