Skip to content

Connection Options ​

Monch provides flexible connection options from zero-config auto-connect to full manual control.

Set MONGODB_URI environment variable. Monch connects on first operation:

bash
# .env
MONGODB_URI=mongodb://localhost:27017/myapp
typescript
// Just use it - no setup required
const user = await Users.insertOne({ name: 'Alice' });

Environment Variable Priority ​

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 (mongodb:// or mongodb+srv://)

Database Name Priority ​

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

Explicit URI ​

Specify the URI in the collection config:

typescript
const Users = collection({
  name: 'users',
  schema: { /* ... */ },
  uri: 'mongodb://localhost:27017/myapp',
});

Shared Client ​

Share a single MongoDB client across collections (recommended for production):

typescript
import { MongoClient } from 'mongodb';

const client = new MongoClient('mongodb://localhost:27017');

const Users = collection({
  name: 'users',
  schema: { /* ... */ },
  client,
  database: 'myapp',
});

const Posts = collection({
  name: 'posts',
  schema: { /* ... */ },
  client,           // Same client
  database: 'myapp',
});

Benefits of Shared Client ​

  • Connection pooling across collections
  • Required for transactions across collections
  • Efficient resource usage

Existing Database Instance ​

If you already have a MongoDB Db instance:

typescript
const db = client.db('myapp');

const Users = collection({
  name: 'users',
  schema: { /* ... */ },
  db,
});

Connection Resolution ​

Monch resolves connections in this order:

  1. Existing Db instance (config.db)
  2. Existing MongoClient (config.client + config.database)
  3. Explicit URI (config.uri)
  4. Environment variables (MONGODB_URI, etc.)

Graceful Shutdown ​

Close all connections when your app shuts down:

typescript
import { disconnectAll } from '@codician-team/monch';

process.on('SIGTERM', async () => {
  console.log('Shutting down...');
  await disconnectAll();
  process.exit(0);
});

Raw MongoDB Access ​

When you need the native MongoDB driver for advanced operations:

typescript
// Get the raw MongoDB collection
const raw = await Users.collection;

// Use any MongoDB driver method
await raw.createIndex({ email: 1 }, { unique: true });
const stats = await raw.stats();
const distinct = await raw.distinct('role');

// Aggregation
const pipeline = [
  { $match: { role: 'admin' } },
  { $group: { _id: '$department', count: { $sum: 1 } } },
];
const results = await raw.aggregate(pipeline).toArray();

// Get the MongoClient
const client = await Users.client;
const admin = client.db().admin();

Connection Pooling ​

MongoDB driver handles connection pooling automatically. Configure pool size in the URI:

bash
# Connection with pool settings
MONGODB_URI=mongodb://localhost:27017/myapp?maxPoolSize=50&minPoolSize=10

Common URI options:

OptionDefaultDescription
maxPoolSize100Maximum connections in pool
minPoolSize0Minimum connections to maintain
maxIdleTimeMS0Max idle time before closing
waitQueueTimeoutMS0Max wait time for connection
connectTimeoutMS30000Initial connection timeout
socketTimeoutMS0Socket timeout

Error Handling ​

Connection errors throw MonchConnectionError:

typescript
import { MonchConnectionError } from '@codician-team/monch';

try {
  const user = await Users.findOne({ email: 'alice@example.com' });
} catch (error) {
  if (error instanceof MonchConnectionError) {
    console.error('Connection failed:', error.message);
    // Handle reconnection or fallback
  }
}

Common connection errors:

  • No MONGODB_URI configured
  • Invalid connection string
  • Network unreachable
  • Authentication failed
  • Database not found

Next.js Considerations ​

Development Mode ​

In development, Next.js hot reloading can create multiple connections. Monch handles this by caching connections, but you may see connection warnings.

Serverless Functions ​

Each serverless function invocation may need to establish a connection. Monch's auto-connect handles this automatically, but for optimal performance:

  1. Use connection pooling via MongoDB Atlas
  2. Consider MongoDB Atlas Serverless
  3. Keep warm connections with scheduled pings

Edge Runtime ​

Edge functions have different runtime constraints. For Edge:

typescript
// Use explicit client with Edge-compatible driver
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI!, {
  // Edge-compatible options
});

Multi-Database Setup ​

Connect to multiple databases:

typescript
const client = new MongoClient('mongodb://localhost:27017');

// Users in 'auth' database
const Users = collection({
  name: 'users',
  schema: { /* ... */ },
  client,
  database: 'auth',
});

// Products in 'shop' database
const Products = collection({
  name: 'products',
  schema: { /* ... */ },
  client,
  database: 'shop',
});

Replica Set Configuration ​

For replica sets (required for transactions):

bash
# Replica set URI
MONGODB_URI=mongodb://host1:27017,host2:27017,host3:27017/myapp?replicaSet=myrs

# MongoDB Atlas (automatically configured)
MONGODB_URI=mongodb+srv://user:password@cluster.mongodb.net/myapp

Released under the MIT License.