feat: adds option to mongoose to ensure indexes (#9155)

Adds option `ensureIndexes` to Mongoose adapter, which will ensure
indexes are ready prior to completing connection.
This commit is contained in:
James Mikrut
2024-11-12 14:42:25 -05:00
committed by GitHub
parent a3ebf51d6e
commit 6bb4067bb3
3 changed files with 26 additions and 0 deletions

View File

@@ -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 })
}

View File

@@ -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: {},

View File

@@ -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 ||