@dev-nat/mongoose
v1.0.0
Published
A lightweight utility for managing Mongoose connections with caching and retries.
Maintainers
Readme
@dev-nat/mongoose
A simple Mongoose utility for initializing database connections.
Features
- Cached Mongoose connections (global singleton)
- Retry mechanism with configurable delay
- Supports multiple MongoDB connections
- Works well in serverless environments
Install
Install using the following commands:
npm install @dev-nat/mongoose
yarn add @dev-nat/mongoose
pnpm add @dev-nat/mongoose
bun add @dev-nat/mongooseBasic Usage
Initialize a Mongoose connection:
// your-db-connection-file.ts
import { createMongooseConnection } from '@dev-nat/mongoose';
export const db = await createMongooseConnection({ uri: 'mongodb://localhost:27017/your-db' });Initialize Mongoose models:
// your-db-models-file.ts
import { Types, Schema, type Model } from 'mongoose';
import { db } from '@your-db-connection-file';
export interface IPerson {
_id: Types.Object.Id;
name: string;
birthDate: Date;
createdAt: Date;
updatedAt: Date;
}
const personSchema = new Schema<IPerson>(
{
name: { type: String, required: true },
birthDate: { type: Date, required: true },
},
{
timestamps: true,
collection: 'person',
},
);
// export the model, db.models checks if the model is already initialized
// db.model initializes the model if not yet
export const Person: Model<IPerson> = db.models.person || db.model('person', personSchema);Initialize multiple connections for multiple MongoDB databases:
// your-db-connection-file.ts
import { createMongooseConnection } from '@dev-nat/mongoose';
export const db1 = await createMongooseConnection({ uri: 'mongodb://localhost:27017/your-db-1' });
export const db2 = await createMongooseConnection({ uri: 'mongodb://localhost:27017/your-db-2' });Start a session and transaction:
// your-database-service-logic.ts
import { db } from '@your-db-connection-file';
import { Person } from '@your-db-models-file';
export async function updateName(personId: string, newName: string) {
// no need to call mongoose.connect()
const session = await db.startSession();
try {
// do not forget to start a transaction
// requires replicaSet to be enabled in MongoDB configuration
session.startTransaction();
// perform the operation
await Person.findByIdAndUpdate(personId, { $set: { name: newName } });
// save changes
await session.commitTransaction();
await session.endSession();
} catch (err) {
console.error(err);
// do not save changes when there is error
await session.abortTransaction();
await session.endSession();
}
}Better Auth integration
To integrate with better-auth, get the MongoClient like the following:
import { betterAuth } from 'better-auth';
import { mongodbAdapter } from 'better-auth/adapters/mongodb';
// you can rename the import to avoid confusion
import { db as connection } from '@your-db-connection-file';
// get the MongoClient
const client = connection.getClient();
const db = client.db();
export const auth = betterAuth({
database: mongodbAdapter(db, { client }),
// the rest of your bettter-auth config
});