MongoDB Database

A modular MongoDB integration for Express with Mongoose, featuring dynamic model registration, CRUD APIs, and built-in support for auth components like auth-jwt.

databasemongodbmongoosecrudjavascriptexpressauthscalable
v3.1.0database

Overview

A powerful, modular MongoDB integration for Express using Mongoose. This component provides a shared database layer that is automatically reused by authentication and other Backternity modules (like auth-jwt, aws-s3-upload, and logger-winston). It supports dynamic model registration and discriminator-based extensions — perfect for scalable systems.

Installation

CLI
npx backternity add database-mongodb

What This Does

Installs a shared MongoDB integration for Express with Mongoose and dynamic model management. Designed to work standalone or as a foundation for other components like auth-jwt.

Files & Folders Created

File / PathDescription
/src/config/database.jsShared MongoDB connection logic.
/src/models/index.jsRegisters base User and Product models.
/src/routes/crud.jsProvides generic CRUD endpoints for all models.
/server.js.exampleExample integration for Express app.
/.env.exampleEnvironment variables for MongoDB configuration.

Files to be modified

File / PathDescription
server.jsAdds MongoDB connection setup.
src/modelsCan be extended dynamically via discriminators.

Configuration

# MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/backternity-app
NODE_ENV=development
PORT=3000

Frontend Integration

You can interact with any registered model (like `User` or `Product`) using these CRUD API endpoints. Below is a Next.js example for fetching, creating, and updating documents.

POST/api/crud/Product

Create a new product document.

GET/api/crud/Product

Fetch all products (supports query filters).

PUT/api/crud/Product/64f8a4b2c1234567890abcde

Update a specific product by its ID.

DELETE/api/crud/Product/64f8a4b2c1234567890abcde

Delete a specific product by its ID.

GET/api/crud/Product/64f8a4b2c1234567890abcde

Fetch a specific product by its ID.

Example

1// app/components/ProductManager.jsx 2'use client'; 3import { useState, useEffect } from 'react'; 4 5export default function ProductManager() { 6 const [products, setProducts] = useState([]); 7 const [form, setForm] = useState({ name: '', price: '' }); 8 9 // Fetch all products 10 async function fetchProducts() { 11 const res = await fetch('/api/crud/Product'); 12 const data = await res.json(); 13 setProducts(data); 14 } 15 16 // Create a new product 17 async function addProduct() { 18 await fetch('/api/crud/Product', { 19 method: 'POST', 20 headers: { 'Content-Type': 'application/json' }, 21 body: JSON.stringify(form) 22 }); 23 setForm({ name: '', price: '' }); 24 fetchProducts(); 25 } 26 27 useEffect(() => { 28 fetchProducts(); 29 }, []); 30 31 return ( 32 <div className="max-w-lg mx-auto bg-black/20 p-6 rounded-xl border border-white/10 text-white space-y-4"> 33 <h2 className="text-xl font-semibold">MongoDB Product Manager</h2> 34 35 <div className="space-y-2"> 36 <input 37 placeholder="Product Name" 38 className="w-full p-2 rounded bg-black/40 border border-white/20 text-white" 39 value={form.name} 40 onChange={(e) => setForm({ ...form, name: e.target.value })} 41 /> 42 <input 43 placeholder="Price" 44 type="number" 45 className="w-full p-2 rounded bg-black/40 border border-white/20 text-white" 46 value={form.price} 47 onChange={(e) => setForm({ ...form, price: e.target.value })} 48 /> 49 <button 50 onClick={addProduct} 51 className="w-full bg-emerald-600 hover:bg-emerald-700 py-2 rounded-md font-semibold" 52 > 53 Add Product 54 </button> 55 </div> 56 57 <div className="mt-6"> 58 <h3 className="text-lg font-medium mb-2">Available Products</h3> 59 {products.length === 0 ? ( 60 <p className="text-sm text-gray-400">No products found.</p> 61 ) : ( 62 <ul className="space-y-1"> 63 {products.map((p) => ( 64 <li 65 key={p._id} 66 className="p-2 bg-black/30 rounded-md border border-white/10" 67 > 68 {p.name} — ₹{p.price} 69 </li> 70 ))} 71 </ul> 72 )} 73 </div> 74 </div> 75 ); 76}

Usage

1// Example CRUD usage in Express 2const express = require('express'); 3const app = express(); 4const crudRoutes = require('./src/routes/crud'); 5const connectMongoDB = require('./src/config/database'); 6connectMongoDB(); 7 8app.use('/api/crud', crudRoutes); 9 10app.listen(3000, () => console.log('MongoDB CRUD API running'));

Get in Touch

For partnerships, collaborations, or custom backend components - let’s build something powerful together.

Send us a message

Reach us directly

Email

team@backternity.dev

Quick Answers

Are components free?

Yes, they’re absolutely free to use.

Do you offer custom work?

Absolutely, we build scalable backend systems tailored to your stack.

How often are updates released?

Monthly, with new components, optimizations, and features.

MongoDB Database – Database Component | Backternity