Esix handles database connections automatically behind the scenes. When you run your first query, Esix establishes a connection to MongoDB and maintains a connection pool for optimal performance. You don’t need to manually create, manage, or close connections in your application code.
import { BaseModel } from 'esix'class User extends BaseModel { public name = '' public email = ''}// No connection yet - just defining the model// Connection is automatically created on first queryconst users = await User.all() // ← Connection established here// Subsequent queries reuse the same connection poolconst user = await User.find('507f1f77bcf86cd799439011')const activeUsers = await User.where('isActive', true).get()
You never need to call connect() or worry about when to establish a connection. Esix handles this automatically.
The ConnectionHandler class manages all database connections. While you rarely need to interact with it directly, it’s available for advanced use cases:
Copy
import { connectionHandler } from 'esix'// Get the active database connectionconst db = await connectionHandler.getConnection()// Access MongoDB API directly if neededconst collection = db.collection('users')const result = await collection.findOne({ email: 'john@example.com' })
While Esix doesn’t natively support multiple simultaneous connections, you can switch databases:
Copy
import { connectionHandler } from 'esix'// Function to switch databasesasync function switchDatabase(databaseName: string) { // Close existing connection await connectionHandler.closeConnections() // Update database name process.env.DB_DATABASE = databaseName // Next query will connect to the new database}// Multi-tenant exampleawait switchDatabase('tenant-1')const tenant1Users = await User.all()await switchDatabase('tenant-2')const tenant2Users = await User.all()
Switching databases requires closing and reopening connections, which has a performance cost. Use this pattern sparingly.
Connections are automatically reused across queries:
Copy
// All these queries reuse connections from the poolconst users = await User.all() // Uses connection 1const posts = await BlogPost.all() // Uses connection 2const products = await Product.all() // Uses connection 3// If pool size is 10, up to 10 concurrent queries can runawait Promise.all([ User.count(), BlogPost.count(), Product.count(), Order.count() // ... up to 10 concurrent queries])
For faster first requests in production, warm up the connection pool:
Copy
import { connectionHandler } from 'esix'// During application startupasync function warmUpConnections() { console.log('Warming up database connections...') await connectionHandler.getConnection() console.log('Database ready')}// Call during app initializationawait warmUpConnections()