Payload CMS Database Integration (MongoDB/PostgreSQL)

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1 servicesAll 2065 services
Payload CMS Database Integration (MongoDB/PostgreSQL)
Medium
from 1 business day to 3 business days
FAQ

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1262
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1171
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    874
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1094
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    831
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    851

PostgreSQL and MongoDB Setup in Payload CMS

Payload 2.x supports two database adapters: PostgreSQL via Drizzle ORM and MongoDB via Mongoose. The choice affects data storage schema, query capabilities, and performance.

PostgreSQL via Drizzle ORM

npm install @payloadcms/db-postgres
// payload.config.ts
import { postgresAdapter } from '@payloadcms/db-postgres'

export default buildConfig({
  db: postgresAdapter({
    pool: {
      connectionString: process.env.DATABASE_URL,
      // Or explicit parameters:
      host: 'localhost',
      port: 5432,
      database: 'payload_db',
      user: 'payload',
      password: process.env.DB_PASSWORD,
      max: 20,           // max connections in pool
      idleTimeoutMillis: 30000,
    },
    push: false,         // don't push schema in production (use migrations)
    migrationDir: './migrations',
  }),
})

Drizzle Migrations:

# Generate migration after collection changes
npx payload migrate:create

# Apply migrations
npx payload migrate

# Rollback
npx payload migrate:down

# Status
npx payload migrate:status

Migrations are saved in ./migrations/*.ts — can be manually edited for complex schema changes.

Storage Schema in PostgreSQL:

-- For posts collection, Payload creates tables:
SELECT table_name FROM information_schema.tables
WHERE table_name LIKE 'posts%';

-- posts                   — main data
-- posts_rels              — relationships (relationship fields)
-- posts_locales           — localized fields (if enabled)
-- _posts_v                — versions (if versioning enabled)
-- _posts_v_locales        — versioned localized fields

Direct Queries via Drizzle:

import { getPayload } from 'payload'
import config from '@payload-config'

const payload = await getPayload({ config })
const drizzle = payload.db.drizzle  // direct access to Drizzle instance

// Raw SQL query
const result = await drizzle.execute(
  sql`SELECT p.*, COUNT(c.id) as comment_count
      FROM posts p
      LEFT JOIN comments c ON c.post_id = p.id
      WHERE p.status = 'published'
      GROUP BY p.id
      ORDER BY comment_count DESC
      LIMIT 10`
)

MongoDB via Mongoose

npm install @payloadcms/db-mongodb
import { mongooseAdapter } from '@payloadcms/db-mongodb'

export default buildConfig({
  db: mongooseAdapter({
    url: process.env.MONGODB_URI!,
    // Connection options
    connectOptions: {
      maxPoolSize: 10,
      serverSelectionTimeoutMS: 5000,
    },
  }),
})

Direct Mongoose Access:

const payload = await getPayload({ config })
const mongoose = payload.db.mongoose  // mongoose instance

// Native MongoDB query
const result = await mongoose.connection.db
  .collection('posts')
  .aggregate([
    { $match: { status: 'published' } },
    { $group: { _id: '$category', count: { $sum: 1 } } },
    { $sort: { count: -1 } },
  ])
  .toArray()

Adapter Comparison

Criterion PostgreSQL MongoDB
Complex relationships Better (JOIN) Via $lookup
Schema Strict, migrations Flexible
Versioning Separate _v tables Separate collections
Localization _locales tables Nested object
Hosting Supabase, Neon, Railway MongoDB Atlas
Production recommendation Yes, for structured data Yes, for flexible schemas

Switching Adapters

Switching adapters after production launch without data migration is not directly possible — export/import via Payload API is required. The choice is made at project start.

Production Setup

// PostgreSQL in production — via SSL and connection pooling
db: postgresAdapter({
  pool: {
    connectionString: process.env.DATABASE_URL,
    ssl: { rejectUnauthorized: true },
    max: 10,
  },
  push: false,  // MUST be false in production
})

// Or via PgBouncer/Supabase Pooler
// connectionString: 'postgresql://user:[email protected]:6543/postgres?pgbouncer=true'

Timeline

Initial database adapter setup with migrations takes 0.5 days. Query optimization and indexing for production takes 1 day.