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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoautocrud

v1.1.1

Published

auto generate the common crud api for mongodb

Downloads

10

Readme

MongoAutoCRUD 🚀 - Auto-Generate MongoDB CRUD APIs

Imagine you’re building the backend for a new project. You have your data schema ready, and now it’s time to write those endless CRUD operations — create, read, update, delete. It feels like the code is on repeat, and your energy is draining fast. What if you could skip all that repetitive work and focus on what really matters?

That's where MongoAutoCRUD steps in, like a reliable assistant who says, "I've got this!" This library will automatically generate the common CRUD API for your MongoDB collections, leaving you with just the creative and strategic tasks. 💡

Let’s dive into the magic of MongoAutoCRUD.

Table of Contents


Installation 📦

First things first, to bring MongoAutoCRUD into your project, you need to install it. Fire up your terminal and run the following command:

npm install mongoautocrud mongoose express

Simple as that, the package is now part of your project’s toolkit.


Quick Start 🏁

So how do you get started? Well, once you’ve installed the package, it’s as easy as calling a few functions and watching the CRUD operations unfold before your eyes.

Here’s your journey to creating a fully functional CRUD API for MongoDB:

1. Import MongoAutoCRUD and Mongoose

Create a new file, let’s say server.js, and start by importing MongoAutoCRUD and setting up the basics.

const { generateCrud } = require('mongoautocrud');
const mongoose = require('mongoose');

2. Define Your Database Connection

The first step is connecting to MongoDB. You define your MongoDB URL, and MongoAutoCRUD will handle the rest.

const dbUrl = 'mongodb://localhost:27017/myDatabase';

3. Set Up Your Schema

Create your collection’s schema definition, just like you would with Mongoose. Here, we’re making an example for Products:

const schemaDefinition = {
  name: { type: String, required: true },
  category: { type: String },
  price: { type: Number, required: true },
};

4. Generate CRUD API

Here’s the magic moment! Call generateCrud to automatically generate your CRUD API. The library will spin up routes for creating, reading, updating, and deleting products:

const collectionName = 'products';

const app = generateCrud({
  dbUrl,
  schemaDefinition,
  collectionName,
});

// Start the server
app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});

5. Your Auto-Generated Endpoints

Once you run the server, MongoAutoCRUD automatically creates the following endpoints:

  • POST /api/products — Create a new product
  • GET /api/products — Read all products
  • GET /api/products/:_id — Read product by ID
  • PUT /api/products/:_id — Update product by ID
  • DELETE /api/products/:_id — Delete product by ID

Plus, you even get category-based endpoints:

  • GET /api/products/category/:category
  • PUT /api/products/category/:category
  • DELETE /api/products/category/:category

Custom Routes 🛠️

Need something more customized? MongoAutoCRUD doesn’t stop at basic CRUD. You can easily add your own custom routes.

Let’s say you want a special route to fetch expensive products (because, let’s face it, luxury sells):

const customRoutes = [
  {
    method: 'get',
    path: '/api/products/expensive',
    handler: async (req, res) => {
      try {
        const expensiveProducts = await Model.find({ price: { $gt: 1000 } });
        res.status(200).send(expensiveProducts);
      } catch (error) {
        res.status(500).send(error);
      }
    },
  },
];

const app = generateCrud({
  dbUrl,
  schemaDefinition,
  collectionName,
  customRoutes,
});

You can now access your custom route at /api/products/expensive. Feel free to add as many custom routes as your project demands.


Features 🎯

  • Auto-Generated CRUD: Get a fully functional API in seconds.
  • Custom Routes: Flexibility to add custom logic and endpoints.
  • Category-Based Filtering: Pre-built routes to manage items by category.
  • Simple and Lightweight: Built on top of Express and Mongoose, MongoAutoCRUD gives you the power of simplicity.

Contributing 🤝

We’re excited about the journey MongoAutoCRUD is on, and we welcome contributions! If you have any ideas to make it even better or find an issue, feel free to open an issue or submit a pull request.

  1. Fork it
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request!

License 📜

This project is licensed under the MIT License. Feel free to use it, modify it, and share it.


That’s it! MongoAutoCRUD is designed to save you time and effort so you can focus on what really matters — building amazing features, not repeating CRUD boilerplate. So, what are you waiting for? 🚀 Dive in, and let MongoAutoCRUD handle the heavy lifting for you.