npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongodb-dynamic-api

v4.23.0

Published

Auto generated CRUD API for MongoDB using NestJS

Readme


[!WARNING] v4 — Breaking changes. Dual-token auth (accessToken + refreshToken), new default expiry (expiresIn: '15m'), 2 new endpoints (/auth/refresh-token, /auth/logout).

🔄 Dual-token authentication

Login and register now return { accessToken, refreshToken } instead of a single token. The /auth/refresh-token endpoint now requires the refresh token.

⏱️ New default expiration times

| Token | v3 | v4 | |---|---|---| | Access token (expiresIn) | '1d' | '15m' | | Refresh token (refreshTokenExpiresIn) | — | '7d' |

If your app relied on the '1d' lifetime, set it explicitly: jwt: { expiresIn: '1d' }.

🆕 Two new endpoints

| Endpoint | Description | |---|---| | POST /auth/refresh-token | Get a new token pair using the refresh token | | POST /auth/logout | Invalidate the refresh token server-side (204 No Content) |

🔒 New options in useAuth

  • jwt.refreshSecret — dedicated signing secret for refresh tokens
  • refreshToken.refreshTokenField — entity field storing the bcrypt hash (server-side revocation)
  • refreshToken.useCookie — send/read refresh token via httpOnly cookie

📖 Full details: README/authentication.md → Migration Guide


✨ Features

🚀 Zero Boilerplate Full CRUD REST API generated from a single schema definition.

🔐 JWT Authentication Dual-token (access + refresh), 8 built-in endpoints, cookie mode, server-side revocation.

🔓 Passwordless / OTP Magic-link / OTP login flow with configurable token delivery.

🛡️ Authorization Ability predicates — per-route access control in filter or throw mode.

Smart Caching Global HTTP cache with auto-invalidation, disableCache per route or controller.

Validation class-validator integration, configurable ValidationPipe globally or per route.

📡 WebSockets Socket.IO support, room-targeted broadcast, onConnection hook, debug mode.

🟢 Presence Real-time online/offline tracking — InMemory or Redis adapter.

🔁 Callbacks beforeSave, afterSave, beforeDelete hooks with typed context + authenticated user.

🌊 Cascade Delete Cross-collection cascades with beforeDeleteCallback and soft-delete support.

🎛️ Custom Routes Add any HTTP method with a custom service and WebSocket gateway in forFeature.

🏷️ Field Decorators @DerivedField for computed values, @ProtectedField for runtime-stripped fields.

🔍 Aggregate + Pagination MongoDB aggregation pipelines via toPipeline, auto-paginated with $facet.

📚 Swagger UI Auto-generated OpenAPI documentation for every route, zero configuration.

All dependencies included — @nestjs/mongoose, @nestjs/jwt, @nestjs/swagger, class-validator, socket.io and more. No extra installs.


⚡ Quick Start

1 — Configure the root module

// src/app.module.ts
import { Module } from '@nestjs/common';
import { DynamicApiModule } from 'mongodb-dynamic-api';

@Module({
  imports: [
    DynamicApiModule.forRoot(process.env.MONGODB_URI),
  ],
})
export class AppModule {}

2 — Define your entity

// src/users/user.entity.ts
import { Prop, Schema } from '@nestjs/mongoose';
import { BaseEntity } from 'mongodb-dynamic-api';
import { IsEmail, IsNotEmpty } from 'class-validator';

@Schema({ collection: 'users' })
export class User extends BaseEntity {
  @IsNotEmpty()
  @Prop({ type: String, required: true })
  name: string;

  @IsEmail()
  @Prop({ type: String, required: true, unique: true })
  email: string;
}

BaseEntity automatically provides id, createdAt, updatedAt and excludes _id / __v from responses.

3 — Generate the API

// src/users/users.module.ts
import { Module } from '@nestjs/common';
import { DynamicApiModule } from 'mongodb-dynamic-api';
import { User } from './user.entity';

@Module({
  imports: [
    DynamicApiModule.forFeature({
      entity: User,
      controllerOptions: { path: 'users' },
    }),
  ],
})
export class UsersModule {}

Register UsersModule in AppModule, run npm run start:dev — your API is live at http://localhost:3000/users. 🎉


📡 Generated Endpoints

| Route Type | Method | Path | Description | |:-----------|:------:|:-----|:------------| | GetMany | GET | /users | List all — supports MongoDB query params | | GetOne | GET | /users/:id | Get a single document by ID | | CreateMany | POST | /users/many | Bulk create — body: { list: User[] } | | CreateOne | POST | /users | Create a single document | | ReplaceOne | PUT | /users/:id | Full replacement | | UpdateMany | PATCH | /users | Partial update — query: ?ids[]= | | UpdateOne | PATCH | /users/:id | Partial update by ID | | DeleteMany | DELETE | /users | Delete multiple — query: ?ids[]= | | DeleteOne | DELETE | /users/:id | Delete by ID | | DuplicateMany | POST | /users/duplicate | Clone multiple with field overrides | | DuplicateOne | POST | /users/duplicate/:id | Clone one with field overrides | | Aggregate | GET | /users/aggregate | Custom aggregation pipeline (requires Query DTO) |

Use the routes array in forFeature to cherry-pick, exclude, or fine-tune any route individually.


📚 Documentation

| Feature | Description | Guide | |:--------|:------------|:-----:| | 🗂️ Entities | BaseEntity, SoftDeletableEntity, timestamps, JSON transform | View | | 🗃️ Schema Options | Indexes, lifecycle hooks, custom schema initialization | View | | 🔐 Authentication | Dual-token JWT, 8 endpoints, cookie mode, revocation, OTP, per-route rate limiting ⭐ | View | | 🛡️ Authorization | Ability predicates, filter vs throw mode | View | | ⚡ Caching | Global cache, auto-purge endpoint, disableCache option ⭐ | View | | ✅ Validation | class-validator, global + per-route ValidationPipe, DB-aware @IsUnique/@EntityExists ⭐ | View | | 📡 WebSockets | Socket.IO, room-targeted broadcast, onConnection, debug ⭐ | View | | 🟢 Presence | Online/offline tracking, InMemory & Redis adapters ⭐ | View | | 🔁 Callbacks | beforeSave, afterSave, beforeDelete, typed contexts ⭐ | View | | 🔄 Versioning | URI-based API versioning | View | | 📚 Swagger UI | Auto-generated OpenAPI docs, visibility decorators | View | | 🗂️ Route Config | DTOs, cascade delete (atomic ⭐), predicates, subPath, interceptors, populate, auditLogNew | View | | 🎛️ Controller Config | forFeature options, customRoutes, extraProviders ⭐ | View | | 🐞 Debugging | MONGODB_DYNAMIC_API_LOGGER levels, WS debug mode, where each log comes from ⭐ | View | | 🩺 Health Check | GET /health readiness probe, DynamicApiHealthModuleNew | View | | 🧪 Testing | createDynamicApiTestingApp, in-memory MongoDB, zero Docker ⭐ New | View | | 🏗️ Schematics | nest g -c mongodb-dynamic-api resource <name> — scaffold entity + module in one command ⭐ New | View |

[!NOTE] Key reminders:

  • BaseEntity auto-enables timestamps — no timestamps: true needed in @Schema()
  • Soft delete: extend SoftDeletableEntity to get isDeleted + deletedAt fields
  • Version strings must be numeric ('1', '2'), not semver
  • WebSocket auth event names are fixed: auth-login, auth-register, auth-refresh-token, auth-logout
  • CRUD WS events auto-generated: kebabCase(routeType + '/' + displayedName)
  • Ability predicate signature: (user, body?) => boolean for auth, (entity, user) => boolean for CRUD

License

MIT — see LICENSE

Made with ❤️ by Mickaël NODANCHE