@hiennc24/mongoose
v2.2.18
Published
Mongoose
Readme
MONGOOSE
TypeScript MongoDB abstraction library with repository pattern, multi-tenancy support, connection pooling, and comprehensive error handling.
INSTALL
npm install @hiennc24/mongooseSETUP
1. Environment Variables
Create a .env file in your project root (copy from .env.example):
cp .env.example .envSet your MongoDB connection string:
MONGODB_URI=mongodb+srv://username:[email protected]/database?retryWrites=true&w=majoritySecurity Note: Never commit .env file with real credentials to version control. The .env file is already in .gitignore.
2. Basic Usage
import { MongoDB, BaseRepository, Schema } from '@hiennc24/mongoose';
// Initialize MongoDB connection
const mongodb = new MongoDB({
// connectionString is automatically loaded from process.env.MONGODB_URI
options: {
maxPoolSize: 10,
minPoolSize: 2
}
});
// Connect to database
await mongodb.connect();
// Define your schema
interface UserEntity {
id: string;
name: string;
email: string;
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true }
});
// Create repository
class UserRepository extends BaseRepository<UserEntity> {
constructor() {
super('user', userSchema, 'users');
}
}
const userRepo = new UserRepository();
// Use repository methods
const user = await userRepo.create({
name: 'John Doe',
email: '[email protected]'
});
const users = await userRepo.findAll({}, { page: 1, limit: 10 });FEATURES
- ✅ Generic repository pattern with TypeScript support
- ✅ Multi-tenancy with orgIds filtering
- ✅ Automatic connection retry with exponential backoff
- ✅ Connection pooling and validation
- ✅ Comprehensive error handling
- ✅ CRUD operations + aggregation/populate
- ✅ Pagination support
- ✅ Transaction support (via session parameter)
TESTING
# Run all tests
npm test
# Run load tests
npm run test:loadLICENSE
ISC
