💾 Database Drivers
Database drivers provide a consistent interface for data persistence in NodeBlocks applications. They abstract the database connection and operations, allowing you to use different databases without changing your business logic.
🎯 Overview
Database drivers in NodeBlocks are factory functions that create configured database instances. They provide:
- Consistent interface across different database types
- Simple configuration with connection strings and database names
- Flexible implementation for custom database adapters
📋 Available Database Drivers
MongoDB Driver
The MongoDB driver creates a configured MongoDB database instance for use with NodeBlocks services.
getMongoClient
Creates a MongoDB database instance with the specified connection URL and database name.
Parameters:
url: string
- MongoDB connection string (e.g.,mongodb://localhost:27017
)dbName: string
- Database name to connect to
Returns: Db
- MongoDB database instance
Usage:
import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';
const client = getMongoClient('mongodb://localhost:27017', 'dev');
const usersCollection = client.collection('users');
Example with Environment Variables:
import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';
const client = getMongoClient(
process.env.MONGODB_URL || 'mongodb://localhost:27017',
process.env.DB_NAME || 'dev'
);
🔧 Using Database Drivers
With Services
Pass database collections to services through the data stores parameter:
import { services } from '@nodeblocks/backend-sdk';
import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';
const client = getMongoClient('mongodb://localhost:27017', 'dev');
express()
.use(
services.userService(
{
users: client.collection('users'),
identity: client.collection('identity'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
}
)
)
.listen(8089);
🔗 Related Documentation
- Using a Custom DataStore - How to implement custom database drivers