Logo

dev-resources.site

for different kinds of informations.

Crudify: Automate Your Mongoose CRUD Operations in NestJS

Published at
1/9/2025
Categories
nestjs
mongodb
mongoose
swagger
Author
mitinoh
Categories
4 categories in total
nestjs
open
mongodb
open
mongoose
open
swagger
open
Author
7 person written this
mitinoh
open
Crudify: Automate Your Mongoose CRUD Operations in NestJS

Are you tired of writing repetitive CRUD logic for your Mongoose models? Meet Crudify, a NestJS library designed to simplify your development workflow by automatically generating RESTful CRUD endpoints. With just a few lines of code, you can set up a fully functional API, complete with Swagger documentation and built-in logging.

📚 What is Crudify?

Crudify is a powerful tool for NestJS developers who work with Mongoose. It reduces boilerplate code by automating the creation of CRUD (Create, Read, Update, Delete) endpoints for your models. But that’s not all! It also provides automatic Swagger documentation and integrates a logger to handle uncaught errors, making your API more maintainable and developer-friendly.

With Crudify, you can:

  • 🚀 Automatically generate CRUD endpoints for your Mongoose models.
  • 📖 Get fully functional Swagger UI without any additional setup.
  • 🛠️ Customize endpoints to fit your specific needs.
  • 🧰 Simplify debugging with integrated logging.

🛠️ Quick Setup

1. Install Dependencies

npm install ncrudify
Enter fullscreen mode Exit fullscreen mode

2. Define Your Model

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class User extends Document {
  @Prop({ required: true }) name: string;
  @Prop({ required: true, unique: true }) email: string;
  @Prop() age: number;
}

export const UserSchema = SchemaFactory.createForClass(User);
Enter fullscreen mode Exit fullscreen mode

3. Create a Service

import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { CrudifyService } from 'ncrudify';

@Injectable()
export class UserService extends CrudifyService<User> {
  constructor(@InjectModel(User.name) userModel: Model<User>) {
    super(userModel);
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Build a Controller

import { Controller } from '@nestjs/common';
import { UserService } from './user.service';
import { Crudify, CrudifyController } from 'ncrudify';

@Crudify({ model: { type: User } })
@Controller('users')
export class UserController extends CrudifyController<User> {
  constructor(public service: UserService) {
    super(service);
  }
}
Enter fullscreen mode Exit fullscreen mode

🌐 Swagger Integration

Crudify makes it effortless to set up Swagger documentation for your API. Swagger automatically documents all your CRUD endpoints, making it easier to test and share your API with your team or external users.

Once set up, you can access the Swagger UI at http://localhost:3000/api, where you’ll find a user-friendly interface to interact with your API.

1. Import CrudifySwaggerModule in AppModule:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CrudifySwaggerModule } from 'ncrudify';

@Module({
  imports: [
    MongooseModule.forRoot(process.env.MONGODB_URI),
    CrudifySwaggerModule,
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

2. Setup Swagger in main.ts:

import { NestFactory } from '@nestjs/core';
import { CrudifySwaggerModule } from 'ncrudify';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  CrudifySwaggerModule.setupSwagger(app);
  await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

🧰 Integrated Logging

Crudify includes a logger to capture and manage uncaught errors, making your debugging process more efficient. The logger is based on Errsole, a tool designed to help developers track runtime errors and improve error handling.

How to Enable the Logger

1. Import CrudifyLoggerModule in AppModule:

import { CrudifyLoggerModule } from 'ncrudify';

@Module({
  imports: [CrudifyLoggerModule],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

2. Access the Logger UI

By default, the Crudify Logger listens on http://localhost:3001. You can access this interface to see all uncaught errors, including stack traces and request details, which makes identifying and fixing issues faster.

Customize the Logger

You can adjust the logger’s configuration by providing custom options, such as log levels or output destinations, to match your project’s needs.


🔎 Advanced Query Filters

Crudify supports powerful query filters using a simple format:

field=[$operator]:value
Enter fullscreen mode Exit fullscreen mode

Examples

  • age=[$gt]:30 - Find users older than 30.
  • name=[$eq]:John - Find users named John.

Supported Operators

  • $eq: Equal to
  • $ne: Not equal to
  • $gt: Greater than
  • $lt: Less than
  • $gte: Greater than or equal to
  • $lte: Less than or equal to
  • $cont: Contains (for strings)
  • $excl: Does not contain (for strings)
  • $in: In a set of values
  • $notin: Not in a set of values
  • $isnull: Is null
  • $notnull: Is not null
  • $between: Between two values

💡 Boost Your Productivity

Crudify is more than just a tool for generating endpoints. It’s a productivity booster for NestJS developers, helping you focus on what matters: building great applications. By handling the repetitive parts of CRUD operations, Swagger setup, and error logging, Crudify saves you time and effort.

👉 GitHub: Crudify

❤️ Support on Buy Me a Coffee.

mongodb Article's
30 articles in total
Favicon
🌐 Building Golang RESTful API with Gin, MongoDB 🌱
Favicon
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb
Favicon
Making a Todo API with FastAPI and MongoDB
Favicon
How to Create and Consume a REST API in Next.js
Favicon
Crudify: Automate Your Mongoose CRUD Operations in NestJS
Favicon
Utilizando la librería Mongoose
Favicon
Full Stack Development (Mern && Flutter)
Favicon
Node.js Meets PostgreSQL and MongoDB in Docker: Docker Diaries
Favicon
Comprendre le Design Pattern MVC avec Node.js, Express et MongoDB
Favicon
Set up MongoDB primary and secondary with Docker.
Favicon
The Intricacies of MongoDB Aggregation Pipeline: Challenges and Insights from Implementing It with Go
Favicon
Test Post
Favicon
Containerizing a MERN Stack Application!
Favicon
MongoDB vs. Couchbase: Comparing Mobile Database Features
Favicon
6 Steps to Set Up MongoDB Atlas for Node.js Applications
Favicon
MongoDB: How to setup replica sets
Favicon
To Dockerize a Node.js and MongoDB CRUD app
Favicon
Day 39: Deploying Stateful Applications with StatefulSets (MongoDB)
Favicon
Do you think schema flexibility justifies using NoSQL? Think twice.
Favicon
HadiDB: A Lightweight, Horizontally Scalable Database in Python
Favicon
A Simple Guide for Choosing the Right Database
Favicon
Integrating MongoDB Atlas Alerts with Lark Custom Bot via AWS Lambda
Favicon
🔍 MongoDB Data Modeling: Embedding vs. Referencing - A Strategic Choice!
Favicon
Unique Index on NULL Values in SQL & NoSQL
Favicon
Embedding vs. Referencing - A Strategic Choice!
Favicon
Series de tiempo en MongoDB
Favicon
I want to write a code for POS sales output interface - and import to mongoDb for sale analysis- however is POS agnostic interface, should work with all POS
Favicon
Hello,help review my fullstack website stack : nestjs,mongodb and reactjs. https://events-org-siiv.vercel.app/
Favicon
Implementing an Express-based REST API in TypeScript with MongoDB, JWT-based Authentication, and RBAC
Favicon
It's a Security Thing.

Featured ones: