Connection Options
Monch provides flexible connection options from zero-config auto-connect to full manual control.
Auto-Connect (Recommended)
Set MONGODB_URI environment variable. Monch connects on first operation:
# .env
MONGODB_URI=mongodb://localhost:27017/myapp// Just use it - no setup required
const user = await Users.insertOne({ name: 'Alice' });Environment Variable Priority
Monch checks these environment variables in order:
MONGODB_URI- Primary connection stringMONGO_URL- Common alternativeDATABASE_URL- Used only if it's a MongoDB URI (mongodb://ormongodb+srv://)
Database Name Priority
- Explicit
databaseconfig option - Database in URI path (e.g.,
mongodb://localhost:27017/mydb) MONGODB_DATABASEorMONGO_DATABASEenvironment variable
Explicit URI
Specify the URI in the collection config:
const Users = collection({
name: 'users',
schema: { /* ... */ },
uri: 'mongodb://localhost:27017/myapp',
});Shared Client
Share a single MongoDB client across collections (recommended for production):
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:
const db = client.db('myapp');
const Users = collection({
name: 'users',
schema: { /* ... */ },
db,
});Connection Resolution
Monch resolves connections in this order:
- Existing
Dbinstance (config.db) - Existing
MongoClient(config.client+config.database) - Explicit URI (
config.uri) - Environment variables (
MONGODB_URI, etc.)
Graceful Shutdown
Close all connections when your app shuts down:
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:
// 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:
# Connection with pool settings
MONGODB_URI=mongodb://localhost:27017/myapp?maxPoolSize=50&minPoolSize=10Common URI options:
| Option | Default | Description |
|---|---|---|
maxPoolSize | 100 | Maximum connections in pool |
minPoolSize | 0 | Minimum connections to maintain |
maxIdleTimeMS | 0 | Max idle time before closing |
waitQueueTimeoutMS | 0 | Max wait time for connection |
connectTimeoutMS | 30000 | Initial connection timeout |
socketTimeoutMS | 0 | Socket timeout |
Error Handling
Connection errors throw MonchConnectionError:
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_URIconfigured - 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:
- Use connection pooling via MongoDB Atlas
- Consider MongoDB Atlas Serverless
- Keep warm connections with scheduled pings
Edge Runtime
Edge functions have different runtime constraints. For Edge:
// 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:
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):
# 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