diff --git a/packages/db-mongodb/src/connect.ts b/packages/db-mongodb/src/connect.ts index 861dd1e909..1268ace4c8 100644 --- a/packages/db-mongodb/src/connect.ts +++ b/packages/db-mongodb/src/connect.ts @@ -57,6 +57,21 @@ export const connect: Connect = async function connect( } } + if (this.ensureIndexes) { + await Promise.all( + this.payload.config.collections.map(async (coll) => { + await new Promise((resolve, reject) => { + this.collections[coll.slug]?.ensureIndexes(function (err) { + if (err) { + reject(err) + } + resolve(true) + }) + }) + }), + ) + } + if (process.env.NODE_ENV === 'production' && this.prodMigrations) { await this.migrate({ migrations: this.prodMigrations }) } diff --git a/packages/db-mongodb/src/index.ts b/packages/db-mongodb/src/index.ts index 7aa0f75d7f..a8e74a1b12 100644 --- a/packages/db-mongodb/src/index.ts +++ b/packages/db-mongodb/src/index.ts @@ -74,8 +74,14 @@ export interface Args { /** Set false to disable $facet aggregation in non-supporting databases, Defaults to true */ useFacet?: boolean } & ConnectOptions + /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */ disableIndexHints?: boolean + /** + * Set to `true` to ensure that indexes are ready before completing connection. + * NOTE: not recommended for production. This can slow down the initialization of Payload. + */ + ensureIndexes?: boolean migrationDir?: string /** * typed as any to avoid dependency @@ -96,6 +102,7 @@ export type MongooseAdapter = { [slug: string]: CollectionModel } connection: Connection + ensureIndexes: boolean globals: GlobalModel mongoMemoryServer: MongoMemoryReplSet prodMigrations?: { @@ -118,6 +125,7 @@ declare module 'payload' { [slug: string]: CollectionModel } connection: Connection + ensureIndexes: boolean globals: GlobalModel mongoMemoryServer: MongoMemoryReplSet prodMigrations?: { @@ -138,6 +146,7 @@ export function mongooseAdapter({ autoPluralization = true, connectOptions, disableIndexHints = false, + ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, @@ -157,6 +166,7 @@ export function mongooseAdapter({ connection: undefined, connectOptions: connectOptions || {}, disableIndexHints, + ensureIndexes, globals: undefined, mongoMemoryServer, sessions: {}, diff --git a/test/generateDatabaseAdapter.ts b/test/generateDatabaseAdapter.ts index 44ffc92eb6..07254be6d1 100644 --- a/test/generateDatabaseAdapter.ts +++ b/test/generateDatabaseAdapter.ts @@ -10,6 +10,7 @@ export const allDatabaseAdapters = { import { mongooseAdapter } from '@payloadcms/db-mongodb' export const databaseAdapter = mongooseAdapter({ + ensureIndexes: true, url: process.env.MONGODB_MEMORY_SERVER_URI || process.env.DATABASE_URI ||