500 UNIVERSE UPDATE ERROR

Ecosistema completo para organización y gestión de contenido con interfaces espaciales

🐛 500 Internal Server Error - Universe Update Troubleshooting

Date: November 18, 2025
Error: PUT /api/spaces/{id}/universes/{id} 500 (Internal Server Error)
Status: 🔍 Debugging in progress


📋 Error Details

From frontend logs:

[SyncEngine] 📤 Calling SpaceApiService.updateUniverse
  └─ dataSize: 1487, hasLayout: true, layoutSections: 2

PUT http://localhost:3000/api/spaces/.../universes/... 500 (Internal Server Error)

[SyncEngine] ❌ Universe update failed

🔍 Step 1: Check Backend Logs

In your backend terminal, look for these logs:

Expected Logs (should appear when you click Save):

[SpacesController] 🌌 Updating universe: { spaceId: '...', universeId: '...' }
[SpacesController] 📦 Universe data keys: id, name, description, layout, ...
[SpacesController] 📐 Has layout: true
[SpacesController] 📏 Layout sections: 2

[SpacesService] Updating universe: universe_... in space: ...
[SpacesService] Universe data size: 1487 bytes
[SpacesService] 📤 Calling spaceDatabaseService.saveUniverseData

[SpaceDatabaseService] 💾 Saving universe data: universe_...
[SpaceDatabaseService] 🔄 Attempting updateOne for universe: universe_...
[SpaceDatabaseService] 📊 Clean data keys: id, name, description, layout, ...
[SpaceDatabaseService] 📏 Clean data size: 1487 bytes

Look for ERROR logs:

❌ MongoDB write error:
  message: "..."
  code: ...
  codeName: "..."

→ Copy the EXACT error message and send it to me!


🔍 Step 2: Run Debug Script in Browser

  1. Open browser console (F12)
  2. Copy and paste this script:
// Run the debug script
fetch('http://localhost:5200/debug-universe-sync.js')
  .then(r => r.text())
  .then(eval);

OR manually run:

const storage = window.GgStorageInstance;
const universeKey = 'universe_universe_1763427157418';

storage.get(universeKey).then(universe => {
  console.log('📦 Universe Data:', universe);
  console.log('📏 Data Size:', JSON.stringify(universe).length, 'bytes');
  console.log('🔍 Layout:', universe.layout);
});

Look for:


🔍 Step 3: Common Issues & Solutions

Issue 1: Space Database Doesn't Exist

Symptom: Backend logs show "database not found" or "collection not found"

Solution: The code should auto-create it, but check:

// In backend logs, look for:
[SpaceDatabaseService] 📦 Database might not exist, creating: space_...
[SpaceDatabaseService] 🔄 Retrying updateOne after creating collection

If this doesn't appear, the error is something else.


Issue 2: Invalid Date Format

Symptom: Backend logs show date-related error

Check: Are createdAt and updatedAt valid dates?

// In browser console:
storage.get('universe_universe_1763427157418').then(u => {
  console.log('createdAt:', u.createdAt, typeof u.createdAt);
  console.log('updatedAt:', u.updatedAt, typeof u.updatedAt);
});

Solution: Already handled in code (converts strings to Date objects)


Issue 3: Undefined Values

Symptom: MongoDB rejects documents with undefined fields

Check: Does the universe object have undefined values?

// In browser console:
storage.get('universe_universe_1763427157418').then(u => {
  const str = JSON.stringify(u);
  console.log('Has undefined:', str.includes('undefined'));
  
  // Find undefined fields
  Object.keys(u).forEach(key => {
    if (u[key] === undefined) {
      console.log('❌ Undefined field:', key);
    }
  });
});

Solution: Already handled in code (removes undefined values)


Issue 4: Data Too Large

Symptom: Data exceeds MongoDB's 16MB document limit

Check:

storage.get('universe_universe_1763427157418').then(u => {
  const size = JSON.stringify(u).length;
  console.log('Data size:', size, 'bytes');
  console.log('MB:', (size / 1024 / 1024).toFixed(2), 'MB');
  
  if (size > 16000000) {
    console.log('❌ EXCEEDS 16MB LIMIT!');
  }
});

Solution: If > 16MB, need to split data into multiple documents


Issue 5: Circular References

Symptom: Cannot stringify object (circular reference)

Check:

try {
  storage.get('universe_universe_1763427157418').then(u => {
    JSON.stringify(u);
    console.log('✅ No circular references');
  });
} catch (e) {
  console.log('❌ Circular reference detected:', e.message);
}

Solution: Need to remove circular references before sending


Issue 6: MongoDB Connection Lost

Symptom: "Cannot connect to MongoDB" in backend logs

Check: Backend terminal shows:

✅ MongoDB connected successfully

If not, restart backend: yarn serve:backend-only


🔧 Quick Fixes

Fix 1: Clear Local Storage and Retry

// In browser console:
localStorage.clear();
location.reload();

// Re-login and try saving again

Fix 2: Check MongoDB Permissions

Ensure your MongoDB user has write permissions:

Fix 3: Restart Backend with Fresh Logs

# Terminal 1: Stop backend (Ctrl+C)
yarn serve:backend-only

# Watch for startup logs

Fix 4: Test with Simple Data

Try saving a universe without complex layout:

// In browser console:
const testUniverse = {
  id: 'test-universe',
  name: 'Test Universe',
  description: 'Simple test',
  spaceId: '69067c087ebb621cd9ff8c3f',
  createdAt: new Date().toISOString(),
  updatedAt: new Date().toISOString()
};

// Try to sync this simple object

📊 Diagnostic Checklist


🎯 Next Steps

  1. Check backend terminal for the detailed error
  2. Copy the exact error message (the ❌ MongoDB write error: part)
  3. Send me the error so I can provide the exact fix

Common errors I can fix:


💡 Pro Tip

Enable verbose MongoDB logging (if needed):

// apis/backend-api/src/app/app.module.ts
MongooseModule.forRootAsync({
  useFactory: async (configService: ConfigService) => ({
    uri: configService.get<string>('MONGODB_CONNECTION_STRING'),
    dbName: configService.get<string>('MONGODB_DATABASE', 'gograb-api'),
    // Add this for debugging:
    connectionFactory: (connection) => {
      connection.plugin((schema) => {
        schema.post('save', (doc) => {
          console.log('📝 Saved:', doc);
        });
      });
      return connection;
    },
  }),
}),

Status: Waiting for backend error details to provide exact fix! 🔍