Database Schema
Overview
This document describes the database schema and data persistence layer for the Customer Management module. The system uses MongoDB as the primary database with Mongoose as the ODM layer, implementing multi-tenant architecture with proper data isolation and validation.
Database Architecture
Technology Stack
Database: MongoDB
ODM: Mongoose
Pattern: Domain-Driven Design (DDD) with CQRS
Multi-Tenancy: Tenant-based data isolation
State Management: Soft delete with state history
Validation: Domain-level validation with schema constraints
Database Schema
Customer Collection
Collection Name: customer
The customer collection stores all customer records with comprehensive customer information for business relationship management.
Schema Definition
Field Specifications
Core Customer Fields
firstName (String, Optional)
Purpose: Customer's first name
Validation: No specific format validation
Usage: Display names, personalization, search
Notes: Part of mandatory field validation (at least one of firstName, lastName, email, phone required)
lastName (String, Optional)
Purpose: Customer's last name
Validation: No specific format validation
Usage: Display names, formal communication, search
Notes: Part of mandatory field validation
phone (String, Optional)
Purpose: Customer contact phone number
Validation:
Format validation using regex pattern
Automatic normalization (numbers only)
International format support
Storage: Normalized format (numbers only)
Usage: Contact, SMS notifications, duplicate detection
Notes: Part of mandatory field validation and uniqueness checks
email (String, Optional)
Purpose: Customer email address
Validation:
Email format validation
Domain validation
Usage: Communication, login, notifications, duplicate detection
Notes: Part of mandatory field validation and uniqueness checks
note (String, Optional)
Purpose: Additional customer information and notes
Validation: No specific validation
Usage: Customer service notes, preferences, special instructions
Notes: Free-form text field for business use
customerType (String, Required with Default)
Purpose: Classification of customer type
Default:
CustomerTypeEnum.regularEnum Values:
regular: Standard registered customersunregistered: Customers with basic informationnew: First-time customersanonymous: Minimal information customers
Usage: Business logic, filtering, reporting
Validation: Must be one of the enum values
System Fields
_id (ObjectId, Auto-generated)
Purpose: Primary key identifier
Generation: MongoDB auto-generated
Format: 24-character hexadecimal string
Usage: Unique customer identification, relationships
Indexing: Automatic primary index
stateHistory (Array, StateHistorySchema)
Purpose: Track customer state changes for soft delete
Default: Empty array
Usage: Soft delete, audit trail, state management
Structure: Array of state change records
Notes: Enables data retention and recovery
createdAt (Date, Auto-generated)
Purpose: Record creation timestamp
Generation: Mongoose automatic timestamp
Usage: Audit trail, reporting, data lifecycle
Format: ISO Date string
updatedAt (Date, Auto-generated)
Purpose: Last modification timestamp
Generation: Mongoose automatic timestamp on updates
Usage: Audit trail, cache invalidation, conflict resolution
Format: ISO Date string
Embedded Schemas
StateHistorySchema
States: Based on EntityStateEnum
active: Normal operational statedeleted: Soft deleted statesuspended: Temporarily inactivearchived: Long-term storage
Validation Rules
Domain-Level Validation
Mandatory Field Validation
At least one of the following fields must be provided:
firstNamelastNameemailphone
Email Validation
Phone Validation
Regular Customer Validation
For CustomerTypeEnum.regular customers, stricter validation applies:
Required fields:
email: Must be provided and validphone: Must be provided and valid
Indexing Strategy
Primary Indexes
Composite Indexes
Performance Optimization Indexes
Query Patterns
Common Queries
Find Customer by ID
Find Customer by Email or Phone
Customer Search with Pagination
Customer Type Statistics
Integration Queries
Customers for Order Processing
First-Time Customer Detection
Multi-Tenancy
Tenant Isolation Strategy
The Customer Management module implements tenant isolation at the application layer rather than database schema level. This approach provides:
Business-Level Isolation: Each business (tenant) has isolated customer data
Shared Database: All tenants share the same MongoDB database
Application Enforcement: Tenant filtering applied in all repository queries
Performance: Optimized queries with tenant-aware indexing
Tenant Context Implementation
Note: Customer records are associated with businesses through the order and service context, not through a direct tenantId field in the customer collection. This design allows customers to potentially interact with multiple businesses while maintaining data integrity.
Data Consistency
Referential Integrity
Customer References in Orders
Orders: Reference customers through embedded customer snapshots
Order Services: Include customer data in attendee arrays
Payment Records: Link to customer information for payer details
Customer Data Snapshots
When customers are referenced in orders or payments, their current data is snapshot:
State Management
Soft Delete Implementation
State History Tracking
State Changes: All state transitions are recorded
Audit Trail: Complete history of customer lifecycle
Recovery: Ability to restore soft-deleted customers
Compliance: Data retention for regulatory requirements
Performance Optimization
Query Optimization
Index Utilization
Pagination Optimization
Memory Management
Field Projection
Aggregation Optimization
Data Migration
Schema Evolution
When schema changes are needed:
Backward Compatible: Add optional fields first
Migration Scripts: Create scripts for data transformation
Field Addition: New fields with defaults
Validation Updates: Enhance validation without breaking existing data
Example Migration Scripts
Add Customer Notes Field
Customer Type Migration
Phone Number Normalization
Backup and Recovery
Backup Strategy
Regular Snapshots: Daily MongoDB snapshots
Point-in-Time Recovery: Enable oplog for PITR
Cross-Region Replication: For disaster recovery
Testing: Regular backup restoration testing
Data Retention
Active Data: Keep in primary collection
Soft Deleted: Retain for compliance period
Hard Delete: After legal retention requirements
Archival: Long-term storage for historical analysis
Security Considerations
Data Protection
PII Handling
Encryption: Sensitive fields encrypted at rest
Access Control: Role-based access to customer data
Audit Logging: All customer data access logged
Data Masking: PII masked in non-production environments
Privacy Compliance
GDPR Support:
Right to Portability: Export customer data
Right to Erasure: Hard delete on request
Consent Tracking: Customer consent preferences
Data Processing: Lawful basis documentation
Implementation Example:
Access Control
Database Security
Authentication: MongoDB authentication required
Authorization: Database-level permissions
Network Security: VPC and firewall protection
Encryption: TLS for data in transit
Application Security
Input Validation: All inputs validated and sanitized
SQL Injection Prevention: Parameterized queries (NoSQL injection)
Rate Limiting: API rate limiting for customer operations
Session Management: Secure session handling
Monitoring and Diagnostics
Performance Monitoring
Key Metrics
Query Performance: Average query execution time
Index Usage: Index hit ratios and efficiency
Collection Growth: Data volume trends
Connection Pool: Database connection utilization
Monitoring Queries
Error Monitoring
Common Issues
Validation Errors: Field format validation failures
Duplicate Detection: Email/phone uniqueness violations
State Consistency: State history integrity issues
Performance: Slow query identification
Diagnostic Queries
Integration Points
Order Management Integration
Customer-Order Relationships
Attendees: Customers linked as service attendees
Payers: Customers linked as payment payers
History: Customer order history tracking
Preferences: Customer service preferences
Data Flow
Payment System Integration
Customer-Payment Relationships
Payer Information: Customer as payment payer
Billing History: Customer payment history
Payment Methods: Customer preferred payment methods
Invoicing: Customer billing information
Notification System Integration
Customer Communication
Email Notifications: Order confirmations, reminders
SMS Notifications: Appointment reminders via phone
Push Notifications: Mobile app notifications
Marketing: Customer segmentation for campaigns
Summary
The Customer Management database schema provides a robust foundation for customer relationship management within the Bee O'clock ecosystem. Key features include:
Flexible Schema: Optional fields supporting various customer types
Data Validation: Comprehensive validation at domain and schema levels
Multi-Tenant Architecture: Business-level data isolation
Performance Optimization: Strategic indexing and query optimization
State Management: Soft delete with complete audit trail
Integration Ready: Seamless integration with orders and payments
GDPR Compliance: Privacy and data protection features
Scalability: Designed for high-volume customer data
Monitoring: Comprehensive performance and error tracking
The schema supports complex business scenarios while maintaining data integrity, performance, and compliance with privacy regulations.
Last updated
Was this helpful?