Skip to main content
Version: 0.6.0 (Latest)

💾 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 MongoDB database client with specified connection URL and database name.

Parameters:

  • url: string - MongoDB connection string (e.g., mongodb://localhost:27017)
  • dbName: string - Database name to connect to within the MongoDB instance

Returns: Db - MongoDB database instance for performing database operations

Usage:

import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';

const db = getMongoClient('mongodb://localhost:27017', 'myapp');

// Access collections
const usersCollection = db.collection('users');
const postsCollection = db.collection('posts');

Example with Environment Variables:

import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';

const db = getMongoClient(
process.env.MONGODB_URL || 'mongodb://localhost:27017',
process.env.DB_NAME || 'myapp'
);

// Use with services
const userService = services.userService({
users: db.collection('users'),
identity: db.collection('identity')
});

Example with MongoDB Atlas:

import { getMongoClient } from '@nodeblocks/backend-sdk/drivers';

const db = getMongoClient(
'mongodb+srv://username:password@cluster.mongodb.net/myapp',
'myapp'
);

🔧 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);