Database Migration & Module Builder

MongoDB database naming migration and module builder enhancement planning

Database Migration & Module Builder Enhancements

🎯 Session Overview

This session focused on two major areas:

  1. MongoDB Database Naming Migration - Implementing a new, readable database naming pattern
  2. Module Builder (modularity-lib) - Continued improvements to the module creation system

✅ Completed Tasks

1. MongoDB Database Naming Pattern Migration

Problem

Solution Implemented

Files Modified

File Changes
apis/backend-api/src/app/spaces/space-database.service.ts Added resolveSpaceDatabaseName() with caching, databaseExists() check
apis/backend-api/src/app/spaces/spaces.schema.ts Added databaseFormat: 'legacy' | 'new' field
apis/backend-api/src/app/spaces/spaces.service.ts Added migrateToNewDatabaseFormat(), auto-healing for empty members
apis/backend-api/src/app/spaces/spaces.controller.ts Added POST /migrate-database endpoint
apis/backend-api/src/app/spaces/space-modules.service.ts Updated to use resolveSpaceDatabaseName()
apis/backend-api/src/app/widgets/widgets.service.ts Updated to use resolveSpaceDatabaseName()
apis/backend-api/src/app/widgets/widgets.module.ts Added SpacesModule import
apis/backend-api/src/app/properties/properties.service.ts Updated to use resolveSpaceDatabaseName()
apis/backend-api/src/app/properties/properties.module.ts Added SpacesModule import
apis/backend-api/src/app/widget-modules/widget-modules.service.ts Updated to use resolveSpaceDatabaseName()
apis/backend-api/src/app/widget-modules/widget-modules.module.ts Added SpacesModule import
apis/backend-api/src/app/data/data.controller.ts Updated to use resolveSpaceDatabaseName()

Key Implementation Details

// SpaceDatabaseService - resolveSpaceDatabaseName()
async resolveSpaceDatabaseName(spaceId: string): Promise<string> {
  // 1. Check cache first - O(1) instant
  const cached = this.dbNameCache.get(spaceId);
  if (cached) return cached;

  // 2. Single indexed query to get space info (~5-10ms)
  const space = await this.spaceModel.findById(spaceId)
    .select('spaceSlug databaseFormat')
    .lean().exec();

  // 3. Determine format based on databaseFormat flag
  let dbName: string;
  if (space?.databaseFormat === 'new' && space?.spaceSlug) {
    dbName = this.getSpaceDatabaseName(spaceId, space.spaceSlug);
  } else {
    dbName = `space_${spaceId}`;
  }

  // 4. Cache forever - all subsequent calls are O(1)
  this.dbNameCache.set(spaceId, dbName);
  return dbName;
}

Migration Endpoint

POST /api/spaces/:spaceId/migrate-database

Copies all collections from old database to new database and updates databaseFormat flag.


2. Auto-Healing Empty Members Array

Problem

Solution

// Before (buggy):
members: (space as any).members || [{ userId: space.ownerId, ... }]

// After (fixed):
const members = (space as any).members?.length > 0 
  ? (space as any).members 
  : [{ userId: space.ownerId, role: 'owner', joinedAt: space.createdAt }];

Plus auto-healing in toResponseWithDetails() that persists the fix to MongoDB.


3. Successfully Migrated Test Space

Property Value
Space ID 69250a03857479fe44376823
Space Slug chrome-space-1
Old Database space_69250a03857479fe44376823
New Database space_chrome-space-1_79fe44376823
Collections Migrated 11
Documents Migrated 34

🚧 Pending Tasks: Module Builder (modularity-lib)

The module builder at libs/libs-structural/modularity-lib/ needs the following improvements:

Step 1: Models Tab

Task Priority Description
AI Intelligence Enhancement 🔴 High AI suggestions need to be smarter - currently showing wrong entity types (e.g., suggesting "Pedo" as entity name from user input)
Entity Type Inference 🔴 High inferFieldType() should use better NLP to understand context
Field Suggestions 🟡 Medium Auto-suggest common fields based on entity name (e.g., "User" → email, password, name)
Validation Rules UI 🟡 Medium Add UI to configure field validation (min, max, pattern, etc.)
Relationship Builder 🟡 Medium Visual way to define relationships between entities

Files to modify:


Step 2: State Tab

Task Priority Description
Collection Config Design 🔴 High Improve design of collection configuration panel
Index Configuration 🟡 Medium Better UI for configuring MongoDB indexes
Cache TTL Selector 🟡 Medium Improve cache TTL dropdown design
Collection Preview 🟢 Low Show preview of how collection will look in MongoDB

Current HTML to improve:

<div class="collection-config">
  Collection Name Override
  Indexes _id (primary) id name
  Cache TTL No caching 1 minute 5 minutes 1 hour
</div>

Files to modify:


Step 3: Actions Tab

Task Priority Description
Visual Flow Builder Canvas 🔴 High Canvas dragging still needs polish
Connection Drawing 🔴 High SVG connectors need improvement
Block Palette 🟡 Medium Add more block types with better categorization
AI Action Suggestions 🟡 Medium Suggest actions based on entities defined
Action Testing 🟢 Low Ability to test actions inline

Files to modify:


Step 4: UI Design Tab

Task Priority Description
Embeddable Creation UX 🔴 High Simplify the embeddable creation process
Widget Integration 🔴 High Better integration with widget system
Live Preview 🟡 Medium Real-time preview of embeddable components
Input/Output Binding 🟡 Medium Visual way to bind inputs/outputs to actions
Template Library 🟢 Low Pre-built embeddable templates

Files to modify:


Step 5: Test Tab

Task Priority Description
Test Runner 🟡 Medium Ability to run tests for module actions
Mock Data Generation 🟡 Medium Auto-generate test data based on entities
Test Results Display 🟢 Low Beautiful test results UI

Step 6: Deploy Tab

Task Priority Description
Export Module 🔴 High Export module as NX library
Version Management 🟡 Medium Semantic versioning support
Dependency Resolution 🟡 Medium Handle module dependencies
Marketplace Integration 🟢 Low Publish to internal marketplace

📁 Key File Locations

Backend (NestJS)

apis/backend-api/src/app/
├── spaces/
│   ├── spaces.controller.ts      # Space API endpoints
│   ├── spaces.service.ts         # Space business logic + migration
│   ├── spaces.schema.ts          # MongoDB schema with databaseFormat
│   ├── space-database.service.ts # Database name resolution + caching
│   └── space-modules.service.ts  # Module CRUD operations
├── widgets/
├── properties/
├── widget-modules/
└── data/

Frontend (Angular)

libs/libs-structural/modularity-lib/src/lib/
├── components/
│   ├── module-workbench/         # Main workbench container
│   ├── steps/
│   │   ├── models-step/          # Entity definition
│   │   ├── state-step/           # State management config
│   │   ├── actions-step/         # Action definition
│   │   ├── ui-step/              # Embeddable components
│   │   ├── test-step/            # Testing
│   │   └── deploy-step/          # Export & deploy
│   └── action-flow-builder/      # Visual flow canvas
├── services/
│   ├── module-context.service.ts # Module state management
│   ├── module-sync.service.ts    # Backend sync
│   ├── ai-reactive-analysis.service.ts # AI analysis
│   └── action-flow-storage.service.ts  # Flow persistence
└── models/
    ├── entity-definition.model.ts
    └── action-flow.model.ts

🔧 Environment Setup

MongoDB Connection

Running the Backend

nx serve backend-api

Running the Frontend

nx serve gograb-space

📝 Notes for Next Session

  1. Don't delete old database yet - Keep space_69250a03857479fe44376823 as backup until fully verified
  2. Test migration on other spaces - The migration endpoint is ready for other spaces
  3. New spaces auto-use new format - Any newly created space will automatically use databaseFormat: 'new'
  4. Performance is optimal - Database name resolution is cached, O(1) after first call

🎯 Ultimate Goal Reminder

"To produce the most advanced, incredible, groundbreaking, intelligent, robust and modern platform builder in the entire universe."

The module builder should enable space-builders to create complex platforms easily through:


Document created: December 3, 2025 Session duration: Extended session covering database migration and module builder improvements