mongodb-multitenant
v1.0.0
Published
Multi-tenant MongoDB connection manager for Node.js/NestJS.
Readme
mongodb-multitenant
Multi-tenant MongoDB connection manager for Node.js and NestJS.
Installation
npm install mongodb-multitenantBasic Usage (Node.js)
import { MongoService } from "mongodb-multitenant";
const mongoService = new MongoService({
mongoUrl: "mongodb://localhost:27017", // required
maxConnections: 30, // optional
connectionTimeoutMs: 15 * 60 * 1000, // optional
mongoClientOptions: { maxPoolSize: 20 }, // optional
});
// Getting a collection (database, collection)
const usersCollection = await mongoService.getCompanyDb("company1", "users");
// Using withConnection
const user = await mongoService.withConnection(
"company1",
"users",
async (col) => {
return await col.findOne({ email: "[email protected]" });
}
);
// Closing all connections (e.g., on shutdown)
await mongoService.closeAllConnections();Options
mongoUrl(required): MongoDB base connection stringmaxConnections: maximum number of concurrent connections (default: 30)connectionTimeoutMs: timeout to consider a connection idle (default: 15 minutes)mongoClientOptions: extra MongoClient options
Usage with NestJS
This library provides a module for easy integration with NestJS:
import { Module } from "@nestjs/common";
import { NestMongoModule, MongoService } from "mongodb-multitenant";
@Module({
imports: [
NestMongoModule.forRoot({
mongoUrl: process.env.MONGODB_URL,
maxConnections: 30,
// ...other options
}),
],
})
export class AppModule {}You can then inject MongoService into your providers/services:
import { Injectable } from "@nestjs/common";
import { MongoService } from "mongodb-multitenant";
@Injectable()
export class UserService {
constructor(private readonly mongoService: MongoService) {}
async getUserByEmail(companyId: string, email: string) {
return this.mongoService.withConnection(
companyId,
"users",
async (col) => await col.findOne({ email })
);
}
}License
MIT
