diff --git a/backend/mongodb/architecture.md b/backend/mongodb/architecture.md new file mode 100644 index 0000000..162f549 --- /dev/null +++ b/backend/mongodb/architecture.md @@ -0,0 +1,104 @@ +--- +description: Vibe coding guidelines and architectural constraints for MongoDB within the backend domain. +technology: MongoDB +domain: backend +level: Senior/Architect +complexity: Advanced +topic: MongoDB Architecture +vibe_coding_ready: true +version: "7.0+" +tags: [architecture-patterns, mongodb, nosql, database, system-design, production-ready, scalable-code] +ai_role: Senior MongoDB Database Architect +last_updated: 2026-03-28 +last_evolution: 2026-03-28 +--- + +# 🏛️ MongoDB Architecture Constraints + +This document provides the "executable blueprints" for MongoDB architecture, outlining folder hierarchies, request/data flows, and entity relationships to ensure AI-agent readiness. + +## 📂 Folder Hierarchy Constraints + +```mermaid +graph TD + classDef domain fill:#f9f,stroke:#333,stroke-width:2px; + classDef core fill:#bbf,stroke:#333,stroke-width:2px; + + src[src] --> domains[domains] + src --> core[core] + + domains --> user[User Domain] + domains --> order[Order Domain] + + user --> schemas[schemas/] + user --> models[models/] + user --> repositories[repositories/] + + core --> database[database/] + database --> connection[connection.ts] + database --> config[config.ts] + + class domains,user,order,schemas,models,repositories domain; + class core,database,connection,config core; +``` + +## 🔄 Request / Data Flow + +```mermaid +sequenceDiagram + participant Client + participant Controller + participant Service + participant Repository + participant Database + + Client->>Controller: POST /api/users (DTO) + Controller->>Service: Create User (Domain Model) + Service->>Repository: Save User (Entity) + Repository->>Database: insertOne() + Database-->>Repository: Acknowledgment (ObjectId) + Repository-->>Service: Saved Entity + Service-->>Controller: Domain Response + Controller-->>Client: 201 Created (Response DTO) +``` + +## 🔗 Entity Relationships + +```mermaid +classDiagram + class User { + +ObjectId _id + +String username + +String email + +String passwordHash + +Date createdAt + +Date updatedAt + +login() + +updateProfile() + } + + class Post { + +ObjectId _id + +ObjectId authorId + +String title + +String content + +Array~ObjectId~ tags + +Date publishedAt + } + + class Comment { + +ObjectId _id + +ObjectId postId + +ObjectId authorId + +String text + +Date createdAt + } + + User "1" --> "*" Post : creates + User "1" --> "*" Comment : writes + Post "1" --> "*" Comment : contains +``` + +--- + +[⬆ Back to Top](#-mongodb-architecture-constraints) diff --git a/backend/mongodb/database-optimization.md b/backend/mongodb/database-optimization.md new file mode 100644 index 0000000..f3c5228 --- /dev/null +++ b/backend/mongodb/database-optimization.md @@ -0,0 +1,102 @@ +--- +description: Vibe coding guidelines and database optimization constraints for MongoDB within the backend domain. +technology: MongoDB +domain: backend +level: Senior/Architect +complexity: Advanced +topic: MongoDB Database Optimization +vibe_coding_ready: true +version: "7.0+" +tags: [database-optimization, mongodb, nosql, indexing, aggregation-pipeline, system-design, production-ready, scalable-code] +ai_role: Senior MongoDB Database Architect +last_updated: 2026-03-28 +last_evolution: 2026-03-28 +--- + +# ⚡ MongoDB Database Optimization Best Practices + +This document outlines indexing strategies (ESR Rule), aggregation pipeline optimization, and query tuning for enterprise-grade MongoDB environments. + +## 🎯 1. The ESR (Equality, Sort, Range) Rule + +When designing indexes, always follow the ESR rule to maximize efficiency. + +### ❌ Bad Practice + +Creating indexes randomly without understanding the query patterns. + +```javascript +// A query with equality, sort, and range: +// db.orders.find({ status: "shipped", amount: { $gt: 100 } }).sort({ date: 1 }) + +// Bad index - Range comes before Sort +db.orders.createIndex({ status: 1, amount: 1, date: 1 }) +``` + +### ✅ Best Practice + +Create indexes following the ESR rule: +1. **E**quality fields first. +2. **S**ort fields next. +3. **R**ange fields last. + +### 🚀 Solution + +```javascript +// Ideal index for the ESR query +db.orders.createIndex({ status: 1, date: 1, amount: 1 }) +``` + +--- + +## 🏗️ 2. Aggregation Pipeline Optimization + +Pipelines process documents in stages. Optimizing the order of these stages dramatically improves performance. + +### ❌ Bad Practice + +Filtering data after heavy transformations or sorting large un-indexed datasets. + +```javascript +db.users.aggregate([ + { $project: { name: 1, age: 1, status: 1 } }, + { $sort: { age: -1 } }, + { $match: { status: "active" } } +]) +``` + +### ✅ Best Practice + +Always use `$match` and `$sort` as early as possible in the pipeline to reduce the working set and take advantage of indexes. Use `$project` later. + +### 🚀 Solution + +```javascript +db.users.aggregate([ + { $match: { status: "active" } }, + { $sort: { age: -1 } }, + { $project: { name: 1, age: 1 } } +]) +``` + +--- + +## 📉 3. Covered Queries + +A covered query is a query that can be satisfied entirely using an index, without having to examine the actual documents. + +### 🚀 Solution + +If you have an index on `{ status: 1, amount: 1 }`: + +```javascript +// This is a covered query because it only projects indexed fields (and explicitly excludes _id) +db.orders.find( + { status: "shipped" }, + { status: 1, amount: 1, _id: 0 } +) +``` + +--- + +[⬆ Back to Top](#-mongodb-database-optimization-best-practices) diff --git a/backend/mongodb/readme.md b/backend/mongodb/readme.md new file mode 100644 index 0000000..eab4d65 --- /dev/null +++ b/backend/mongodb/readme.md @@ -0,0 +1,86 @@ +--- +description: Vibe coding guidelines and architectural constraints for MongoDB within the backend domain. +technology: MongoDB +domain: backend +level: Senior/Architect +complexity: Advanced +topic: MongoDB +vibe_coding_ready: true +version: "7.0+" +tags: [best-practices, clean-code, architecture-patterns, vibe-coding, mongodb, nosql, database, system-design, production-ready, scalable-code, document-database] +ai_role: Senior MongoDB Database Architect +last_updated: 2026-03-28 +last_evolution: 2026-03-28 +--- + +
+ MongoDB Logo + + # 🍃 MongoDB Production-Ready Best Practices +
+ +--- + +This document establishes **best practices** for building and maintaining MongoDB databases. These constraints guarantee a scalable, highly secure, and clean architecture suitable for an enterprise-level, production-ready backend. + +# ⚙️ Context & Scope +- **Primary Goal:** Provide an uncompromising set of rules and architectural constraints for MongoDB environments. +- **Target Tooling:** AI-agents (Cursor, Windsurf, Copilot, Antigravity) and Senior Database Administrators. +- **Tech Stack Version:** MongoDB 7.0+ + +> [!IMPORTANT] +> **Architectural Contract:** MongoDB is schema-less by nature, but production applications require strict schema validation at the database level and through ORM/ODMs like Mongoose. Never allow unstructured data to enter the persistence layer without validation. + +--- + +## 📚 Specialized Documentation + +For deep dives into specific topics, consult the specialized guides: + +- 🏛️ [**Architecture & Design**](./architecture.md): Boundary definitions, entity relationships, and structural constraints. +- ⚡ [**Database Optimization**](./database-optimization.md): Indexing strategies (ESR Rule) and aggregation pipelines. +- 🔒 [**Security Best Practices**](./security-best-practices.md): RBAC, field-level encryption, and NoSQL injection prevention. + +--- + +## 🏗️ Core Principles + +### 🚨 1. Schema Validation +#### ❌ Bad Practice +```javascript +// Inserting data without validation +db.users.insertOne({ name: "John", age: -5, admin: true }); +``` +#### ✅ Best Practice +Implement strict schema validation using JSON Schema in MongoDB. +#### 🚀 Solution +```javascript +db.createCollection("users", { + validator: { + $jsonSchema: { + bsonType: "object", + required: ["name", "email"], + properties: { + name: { + bsonType: "string", + description: "must be a string and is required" + }, + email: { + bsonType: "string", + pattern: "^.+@.+\\..+$", + description: "must be a valid email and is required" + }, + age: { + bsonType: "int", + minimum: 0, + description: "must be an integer greater than or equal to 0" + } + } + } + } +}); +``` + +--- + +[⬆ Back to Top](#-mongodb-production-ready-best-practices) diff --git a/backend/mongodb/security-best-practices.md b/backend/mongodb/security-best-practices.md new file mode 100644 index 0000000..000b1ff --- /dev/null +++ b/backend/mongodb/security-best-practices.md @@ -0,0 +1,118 @@ +--- +description: Vibe coding guidelines and security constraints for MongoDB within the backend domain. +technology: MongoDB +domain: backend +level: Senior/Architect +complexity: Advanced +topic: MongoDB Security Best Practices +vibe_coding_ready: true +version: "7.0+" +tags: [security-best-practices, mongodb, nosql, database, authentication, authorization, rbac, encryption, injection-prevention, production-ready, scalable-code] +ai_role: Senior MongoDB Database Architect +last_updated: 2026-03-28 +last_evolution: 2026-03-28 +--- + +# 🔒 MongoDB Security Best Practices + +This document outlines essential security controls for enterprise-level MongoDB deployments, focusing on RBAC, encryption at rest, and preventing NoSQL injections. + +## 🛡️ 1. Authentication and Authorization (RBAC) + +Ensure MongoDB requires authentication and enforce Role-Based Access Control (RBAC) to limit privileges to the absolute minimum necessary. + +### ❌ Bad Practice + +Running MongoDB with authorization disabled or using powerful built-in roles (e.g., `root`, `dbAdminAnyDatabase`) for application connections. + +```javascript +// A common mistake is using the root user for application access +db.createUser({ user: "appUser", pwd: "secretPassword", roles: ["root"] }) +``` + +### ✅ Best Practice + +Enable authorization in `mongod.conf` (`security.authorization: enabled`) and create custom roles or use the principle of least privilege. + +### 🚀 Solution + +```javascript +// Grant read/write access to specific collections only +db.createRole({ + role: "appRole", + privileges: [ + { resource: { db: "appDB", collection: "users" }, actions: ["find", "insert", "update", "remove"] }, + { resource: { db: "appDB", collection: "logs" }, actions: ["insert"] } + ], + roles: [] +}); + +db.createUser({ + user: "appUser", + pwd: "secretPassword", + roles: [ { role: "appRole", db: "appDB" } ] +}); +``` + +--- + +## 🔐 2. NoSQL Injection Prevention + +MongoDB queries can be vulnerable to NoSQL injection if user input is not properly sanitized or if raw operator objects are passed directly to query parameters. + +### ❌ Bad Practice + +Directly passing unsanitized user input (e.g., from a web request) into a MongoDB query. + +```javascript +// Express.js example: Vulnerable to NoSQL Injection +// If req.body.username = { "$gt": "" }, it matches any username +const user = await db.collection('users').findOne({ + username: req.body.username, + password: req.body.password +}); +``` + +### ✅ Best Practice + +Validate and sanitize all inputs to ensure they are primitives (strings, numbers, booleans) and not MongoDB query objects (objects containing `$` operators). + +### 🚀 Solution + +Using a library like `express-mongo-sanitize` to strip out keys beginning with `$` or `.`. + +```javascript +// Express.js with express-mongo-sanitize +const mongoSanitize = require('express-mongo-sanitize'); +app.use(mongoSanitize()); // Automatically removes $ and . from req.body, req.query, req.params + +// The query is now safer because operators have been stripped +const user = await db.collection('users').findOne({ + username: String(req.body.username), + password: String(req.body.password) +}); +``` + +--- + +## 🗄️ 3. Encryption at Rest + +Protect data stored on disk by enabling encryption at rest, ensuring that unauthorized parties cannot access the database files if the host is compromised. + +### ✅ Best Practice + +Enable WiredTiger encryption at rest using a robust Key Management Service (KMS). + +### 🚀 Configuration + +```yaml +# mongod.conf +security: + enableEncryption: true + encryptionCipherMode: AES256-CBC + encryptionKeyFile: /path/to/master/key/file +``` + +--- + +[⬆ Back to Top](#-mongodb-security-best-practices) diff --git a/backend/readme.md b/backend/readme.md index 6b3343c..f39e643 100644 --- a/backend/readme.md +++ b/backend/readme.md @@ -39,10 +39,12 @@ last_updated: 2026-03-22 ## Technologies Included + This folder acts as a container for documentation around the following backend technologies: - [NestJS](./nestjs/readme.md) - [ExpressJS](./expressjs/readme.md) - [Node.js](./nodejs/readme.md) - [PostgreSQL](./postgresql/readme.md) +- [MongoDB](./mongodb/readme.md) - [Redis](./redis/readme.md) - [Microservices](./microservices/readme.md)