Migrating from MongoDB to PostgreSQL

diy-analytics stores all data in PostgreSQL via Drizzle ORM. If you're upgrading from a legacy release (v0.1.0 or earlier) that used MongoDB, this guide walks you through moving your workspaces, projects, goals, alerts, funnels, pageviews, and custom events over using the automated migration script.


Before you start

  • MongoDB stays untouched. The migration script only reads from MongoDB and writes new records to PostgreSQL. Your source database is never mutated.
  • Sessions get invalidated. Users log in again once after cutover — session tokens are short-lived and don't transfer across database engines.
  • Safe for production datasets. The script streams large pageviews and events collections in batches rather than loading them into memory.

Migration steps

1. Provision a PostgreSQL database

Set up PostgreSQL 14+ with connection pooling enabled — Neon, Supabase, or Vercel Postgres all work.

2. Configure DATABASE_URL

Add your pooled connection string to .env.local:

bash
DATABASE_URL=postgres://user:password@ep-xxxx-pooler.us-east-2.aws.neon.tech/neondb?sslmode=require

3. Keep your MongoDB variables for now

The migration runner needs them to read your legacy data:

bash
1MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/?retryWrites=true&w=majority 2MONGODB_DATABASE=diy-analytics

4. Apply the PostgreSQL schema

bash
npm run db:migrate

5. Run the migration script

bash
npm run db:migrate-from-mongo

Under the hood, it:

  1. Translates IDs. Converts MongoDB ObjectId strings into PostgreSQL UUID primary keys.
  2. Preserves relationships. Updates every foreign key across Workspace → Project → Goals, Funnels, Pageviews, Events.
  3. Logs failures separately. Invalid records that fail migration are written to migration-errors.log in your project root instead of halting the run.
  4. Summarizes the result. Prints a side-by-side row-count comparison when it finishes.

6. Verify row counts

Check the console summary to confirm table counts match between MongoDB and PostgreSQL.

7. Remove the MongoDB variables

Once verified:

  1. Remove MONGODB_URI and MONGODB_DATABASE from your environment.
  2. Trigger a production redeploy on Vercel.

8. Log in

Sign into your dashboard with your existing credentials and confirm your analytics are intact.


Renamed environment variables

Old (MongoDB)New (PostgreSQL)
MONGODB_URIDATABASE_URL
MONGODB_DATABASEEmbedded in DATABASE_URL connection path
MONGODB_STORAGE_CAP_MBDATABASE_STORAGE_CAP_MB

Next steps