@payloadcms/db-mongodb 4.0.0-beta.3 → 4.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/predefinedMigrations/migrateSizesToVariants.ts"],"sourcesContent":["import type {\n Collection,\n CreateIndexesOptions,\n Document,\n IndexDescriptionInfo,\n IndexDirection,\n} from 'mongodb'\nimport type { Payload, PayloadRequest } from 'payload'\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { getSession } from '../utilities/getSession.js'\n\n/** Mongo error codes for an index that conflicts with an existing index. */\nconst INDEX_CONFLICT_CODES = new Set([85, 86])\n/** Mongo error code for a collection that hasn't been created yet. */\nconst NAMESPACE_NOT_FOUND_CODE = 26\nconst GENERATED_VARIANT_METADATA_FIELDS = new Set([\n 'filename',\n 'filesize',\n 'height',\n 'mimeType',\n 'url',\n 'width',\n])\n\n/**\n * Moves every upload collection's stored image sizes between the legacy `sizes` field and\n * `variants`, on each collection and its versions collection (`version.sizes`). Uses `$rename`,\n * so no document is rewritten beyond the renamed key, and re-keys the indexes on those fields.\n * Documents that are already renamed are left as they are, so it's safe to re-run.\n */\nexport async function migrateSizesToVariants({\n direction = 'up',\n payload,\n req,\n}: {\n direction?: 'down' | 'up'\n payload: Payload\n req?: Partial<PayloadRequest>\n}): Promise<void> {\n const adapter = payload.db as unknown as MongooseAdapter\n const session = await getSession(adapter, req)\n const [from, to] = direction === 'up' ? ['sizes', 'variants'] : ['variants', 'sizes']\n\n const targets: {\n collection: Collection\n expectedVariantNames: string[]\n fromPath: string\n toPath: string\n }[] = []\n\n for (const collection of payload.config.collections) {\n if (!collection.upload) {\n continue\n }\n\n const upload = typeof collection.upload === 'object' ? collection.upload : undefined\n const expectedVariantNames = (upload?.variants ?? []).map(({ name }) => name)\n\n targets.push({\n collection: adapter.collections[collection.slug]!.collection,\n expectedVariantNames,\n fromPath: from,\n toPath: to,\n })\n\n if (collection.versions && adapter.versions[collection.slug]) {\n targets.push({\n collection: adapter.versions[collection.slug]!.collection,\n expectedVariantNames,\n fromPath: `version.${from}`,\n toPath: `version.${to}`,\n })\n }\n }\n\n for (const { collection, expectedVariantNames, fromPath, toPath } of targets) {\n const [sourceData, directCollision] = await Promise.all([\n collection.findOne({ [fromPath]: { $exists: true } }, { projection: { _id: 1 } }),\n collection.findOne(\n { [fromPath]: { $exists: true }, [toPath]: { $exists: true } },\n { projection: { _id: 1 } },\n ),\n ])\n\n if (\n sourceData &&\n (directCollision ||\n (await findUnexpectedDestinationData({ collection, expectedVariantNames, toPath })))\n ) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because collection \"${collection.collectionName}\" contains both \"${fromPath}\" and \"${toPath}\" data. Move or rename the existing destination data before running this migration.`,\n )\n }\n }\n\n // Index changes can't be part of a multi-document transaction, and one made after the\n // migration's transaction has written to a collection aborts it. A transaction's snapshot starts\n // at its first operation, so re-keying every index before any transactional write is safe.\n for (const target of targets) {\n await rekeyIndexes(target)\n }\n\n for (const { collection, fromPath, toPath } of targets) {\n const result = await collection.updateMany(\n { [fromPath]: { $exists: true }, [toPath]: { $exists: false } },\n { $rename: { [fromPath]: toPath } },\n { session },\n )\n\n payload.logger.info({\n msg: `sizes-to-variants (${direction}): renamed ${fromPath} on ${result.modifiedCount} document(s) in \"${collection.collectionName}\"`,\n })\n }\n}\n\nasync function findUnexpectedDestinationData({\n collection,\n expectedVariantNames,\n toPath,\n}: {\n collection: Collection\n expectedVariantNames: string[]\n toPath: string\n}): Promise<Document | null> {\n const expectedVariantNameSet = new Set(expectedVariantNames)\n const cursor = collection.find(\n { [toPath]: { $exists: true } },\n { projection: { _id: 1, [toPath]: 1 } },\n )\n\n try {\n for await (const document of cursor) {\n const destinationData = getDocumentPath({ document, path: toPath })\n\n if (hasUnexpectedVariantData({ destinationData, expectedVariantNameSet })) {\n return document\n }\n }\n } finally {\n await cursor.close()\n }\n\n return null\n}\n\nfunction getDocumentPath({ document, path }: { document: Document; path: string }): unknown {\n return path.split('.').reduce<unknown>((value, pathSegment) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n return value[pathSegment]\n }, document)\n}\n\nfunction hasUnexpectedVariantData({\n destinationData,\n expectedVariantNameSet,\n}: {\n destinationData: unknown\n expectedVariantNameSet: Set<string>\n}): boolean {\n if (!isRecord(destinationData)) {\n return destinationData !== null && destinationData !== undefined\n }\n\n for (const [variantName, variantData] of Object.entries(destinationData)) {\n if (!expectedVariantNameSet.has(variantName)) {\n return true\n }\n\n if (variantData === null || variantData === undefined) {\n continue\n }\n\n if (\n !isRecord(variantData) ||\n Object.keys(variantData).some(\n (metadataFieldName) => !GENERATED_VARIANT_METADATA_FIELDS.has(metadataFieldName),\n )\n ) {\n return true\n }\n }\n\n return false\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nasync function rekeyIndexes({\n collection,\n fromPath,\n toPath,\n}: {\n collection: Collection\n fromPath: string\n toPath: string\n}): Promise<void> {\n let indexes: IndexDescriptionInfo[]\n\n try {\n indexes = await collection.indexes()\n } catch (err) {\n if ((err as { code?: number }).code === NAMESPACE_NOT_FOUND_CODE) {\n return\n }\n\n throw err\n }\n\n for (const index of indexes) {\n const sourceKeys = getIndexKeysForCreate({ fromPath, index, toPath: fromPath })\n\n if (!Object.keys(sourceKeys).some((key) => isPathAtOrBelow({ key, path: fromPath }))) {\n continue\n }\n\n const rekeyedKeys = getIndexKeysForCreate({ fromPath, index, toPath })\n const destinationOptions = getDestinationIndexOptions({ fromPath, index, toPath })\n\n if (index.weights && '_fts' in index.key && '_ftsx' in index.key) {\n await rekeyTextIndex({\n collection,\n destinationOptions,\n index,\n rekeyedKeys,\n sourceKeys,\n })\n continue\n }\n\n try {\n await collection.createIndex(rekeyedKeys, destinationOptions)\n } catch (err) {\n if (!INDEX_CONFLICT_CODES.has((err as { code?: number }).code ?? 0)) {\n throw err\n }\n\n const destinationIndex = (await collection.indexes()).find((candidate) =>\n isDeepStrictEqual(\n getIndexKeysForCreate({ fromPath: toPath, index: candidate, toPath }),\n rekeyedKeys,\n ),\n )\n const existingDestinationOptions = destinationIndex\n ? getDestinationIndexOptions({\n fromPath: toPath,\n index: destinationIndex,\n toPath,\n })\n : undefined\n\n if (!destinationIndex || !isDeepStrictEqual(existingDestinationOptions, destinationOptions)) {\n throw err\n }\n }\n\n await collection.dropIndex(index.name!)\n }\n}\n\nasync function rekeyTextIndex({\n collection,\n destinationOptions,\n index,\n rekeyedKeys,\n sourceKeys,\n}: {\n collection: Collection\n destinationOptions: CreateIndexesOptions\n index: IndexDescriptionInfo\n rekeyedKeys: Record<string, IndexDirection>\n sourceKeys: Record<string, IndexDirection>\n}): Promise<void> {\n if (!index.name) {\n throw new Error('Cannot re-key an unnamed MongoDB text index.')\n }\n\n const sourceOptions: CreateIndexesOptions = {\n ...getDestinationIndexOptions({ fromPath: '', index, toPath: '' }),\n name: index.name,\n }\n\n await collection.dropIndex(index.name)\n\n try {\n await collection.createIndex(rekeyedKeys, destinationOptions)\n } catch (err) {\n try {\n await collection.createIndex(sourceKeys, sourceOptions)\n } catch (restoreErr) {\n throw new AggregateError(\n [err, restoreErr],\n `Failed to create the replacement for MongoDB text index \"${index.name}\" and failed to restore the source index.`,\n )\n }\n\n throw err\n }\n}\n\nfunction getIndexKeysForCreate({\n fromPath,\n index,\n toPath,\n}: {\n fromPath: string\n index: IndexDescriptionInfo\n toPath: string\n}): Record<string, IndexDirection> {\n const keys: [string, IndexDirection][] = []\n const hasInternalTextKeys = '_fts' in index.key && '_ftsx' in index.key\n\n for (const [key, value] of Object.entries(index.key)) {\n if (hasInternalTextKeys && key === '_fts') {\n for (const textPath of Object.keys(index.weights ?? {})) {\n keys.push([rekeyPath({ fromPath, path: textPath, toPath }), 'text'])\n }\n continue\n }\n\n if (hasInternalTextKeys && key === '_ftsx') {\n continue\n }\n\n keys.push([rekeyPath({ fromPath, path: key, toPath }), value])\n }\n\n return Object.fromEntries(keys)\n}\n\nfunction getDestinationIndexOptions({\n fromPath,\n index,\n toPath,\n}: {\n fromPath: string\n index: IndexDescriptionInfo\n toPath: string\n}): CreateIndexesOptions {\n const options: CreateIndexesOptions = {\n '2dsphereIndexVersion': index['2dsphereIndexVersion'],\n background: index.background,\n bits: index.bits,\n bucketSize: index.bucketSize,\n collation: index.collation,\n default_language: index.default_language,\n expireAfterSeconds: index.expireAfterSeconds,\n hidden: index.hidden,\n language_override: index.language_override,\n max: index.max,\n min: index.min,\n partialFilterExpression: index.partialFilterExpression\n ? rekeyDocumentPaths({ document: index.partialFilterExpression, fromPath, toPath })\n : undefined,\n sparse: index.sparse,\n storageEngine: index.storageEngine,\n textIndexVersion: index.textIndexVersion,\n unique: index.unique,\n weights: index.weights\n ? rekeyDocumentPaths({ document: index.weights, fromPath, toPath })\n : undefined,\n wildcardProjection: index.wildcardProjection\n ? rekeyDocumentPaths({ document: index.wildcardProjection, fromPath, toPath })\n : undefined,\n }\n\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined),\n ) as CreateIndexesOptions\n}\n\nfunction rekeyDocumentPaths({\n document,\n fromPath,\n toPath,\n}: {\n document: Document\n fromPath: string\n toPath: string\n}): Document {\n return Object.fromEntries(\n Object.entries(document).map(([key, value]) => [\n rekeyPath({ fromPath, path: key, toPath }),\n rekeyDocumentValue({ fromPath, toPath, value }),\n ]),\n )\n}\n\nfunction isPathAtOrBelow({ key, path }: { key: string; path: string }): boolean {\n return key === path || key.startsWith(`${path}.`)\n}\n\nfunction rekeyPath({\n fromPath,\n path,\n toPath,\n}: {\n fromPath: string\n path: string\n toPath: string\n}): string {\n return isPathAtOrBelow({ key: path, path: fromPath })\n ? `${toPath}${path.slice(fromPath.length)}`\n : path\n}\n\nfunction rekeyDocumentValue({\n fromPath,\n toPath,\n value,\n}: {\n fromPath: string\n toPath: string\n value: unknown\n}): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => rekeyDocumentValue({ fromPath, toPath, value: item }))\n }\n\n if (\n value !== null &&\n typeof value === 'object' &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n ) {\n return rekeyDocumentPaths({ document: value as Document, fromPath, toPath })\n }\n\n return value\n}\n"],"names":["isDeepStrictEqual","getSession","INDEX_CONFLICT_CODES","Set","NAMESPACE_NOT_FOUND_CODE","GENERATED_VARIANT_METADATA_FIELDS","migrateSizesToVariants","direction","payload","req","adapter","db","session","from","to","targets","collection","config","collections","upload","undefined","expectedVariantNames","variants","map","name","push","slug","fromPath","toPath","versions","sourceData","directCollision","Promise","all","findOne","$exists","projection","_id","findUnexpectedDestinationData","Error","collectionName","target","rekeyIndexes","result","updateMany","$rename","logger","info","msg","modifiedCount","expectedVariantNameSet","cursor","find","document","destinationData","getDocumentPath","path","hasUnexpectedVariantData","close","split","reduce","value","pathSegment","isRecord","variantName","variantData","Object","entries","has","keys","some","metadataFieldName","Array","isArray","indexes","err","code","index","sourceKeys","getIndexKeysForCreate","key","isPathAtOrBelow","rekeyedKeys","destinationOptions","getDestinationIndexOptions","weights","rekeyTextIndex","createIndex","destinationIndex","candidate","existingDestinationOptions","dropIndex","sourceOptions","restoreErr","AggregateError","hasInternalTextKeys","textPath","rekeyPath","fromEntries","options","background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","rekeyDocumentPaths","sparse","storageEngine","textIndexVersion","unique","wildcardProjection","filter","rekeyDocumentValue","startsWith","slice","length","item","getPrototypeOf","prototype"],"mappings":"AASA,SAASA,iBAAiB,QAAQ,YAAW;AAI7C,SAASC,UAAU,QAAQ,6BAA4B;AAEvD,0EAA0E,GAC1E,MAAMC,uBAAuB,IAAIC,IAAI;IAAC;IAAI;CAAG;AAC7C,oEAAoE,GACpE,MAAMC,2BAA2B;AACjC,MAAMC,oCAAoC,IAAIF,IAAI;IAChD;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;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AC1B1D,QAAQ,EACR1B,QAAQ,EACRC,MAAM,EAKP;IACC,OAAOsC,OAAOgC,WAAW,CACvBhC,OAAOC,OAAO,CAACd,UAAU9B,GAAG,CAAC,CAAC,CAACyD,KAAKnB,MAAM,GAAK;YAC7CoC,UAAU;gBAAEtE;gBAAU6B,MAAMwB;gBAAKpD;YAAO;YACxC0F,mBAAmB;gBAAE3F;gBAAUC;gBAAQiC;YAAM;SAC9C;AAEL;AAEA,SAASoB,gBAAgB,EAAED,GAAG,EAAExB,IAAI,EAAiC;IACnE,OAAOwB,QAAQxB,QAAQwB,IAAIuC,UAAU,CAAC,GAAG/D,KAAK,CAAC,CAAC;AAClD;AAEA,SAASyC,UAAU,EACjBtE,QAAQ,EACR6B,IAAI,EACJ5B,MAAM,EAKP;IACC,OAAOqD,gBAAgB;QAAED,KAAKxB;QAAMA,MAAM7B;IAAS,KAC/C,GAAGC,SAAS4B,KAAKgE,KAAK,CAAC7F,SAAS8F,MAAM,GAAG,GACzCjE;AACN;AAEA,SAAS8D,mBAAmB,EAC1B3F,QAAQ,EACRC,MAAM,EACNiC,KAAK,EAKN;IACC,IAAIW,MAAMC,OAAO,CAACZ,QAAQ;QACxB,OAAOA,MAAMtC,GAAG,CAAC,CAACmG,OAASJ,mBAAmB;gBAAE3F;gBAAUC;gBAAQiC,OAAO6D;YAAK;IAChF;IAEA,IACE7D,UAAU,QACV,OAAOA,UAAU,YAChBK,CAAAA,OAAOyD,cAAc,CAAC9D,WAAWK,OAAO0D,SAAS,IAAI1D,OAAOyD,cAAc,CAAC9D,WAAW,IAAG,GAC1F;QACA,OAAOkD,mBAAmB;YAAE1D,UAAUQ;YAAmBlC;YAAUC;QAAO;IAC5E;IAEA,OAAOiC;AACT"}
1
+ {"version":3,"sources":["../../src/predefinedMigrations/migrateSizesToVariants.ts"],"sourcesContent":["import type {\n Collection,\n CreateIndexesOptions,\n Document,\n IndexDescriptionInfo,\n IndexDirection,\n} from 'mongodb'\nimport type { Payload, PayloadRequest } from 'payload'\n\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { MongooseAdapter } from '../index.js'\n\nimport { getSession } from '../utilities/getSession.js'\n\n/** Mongo error codes for an index that conflicts with an existing index. */\nconst INDEX_CONFLICT_CODES = new Set([85, 86])\n/** Mongo error code for a collection that hasn't been created yet. */\nconst NAMESPACE_NOT_FOUND_CODE = 26\nconst GENERATED_VARIANT_METADATA_FIELDS = new Set([\n 'filename',\n 'filesize',\n 'height',\n 'mimeType',\n 'url',\n 'width',\n])\n\n/**\n * Moves every upload collection's stored image sizes between the legacy `sizes` field and\n * `variants`, on each collection and its versions collection (`version.sizes`). Uses `$rename`,\n * so no document is rewritten beyond the renamed key, and re-keys the indexes on those fields.\n * Documents that are already renamed are left as they are, so it's safe to re-run.\n */\nexport async function migrateSizesToVariants({\n direction = 'up',\n payload,\n req,\n}: {\n direction?: 'down' | 'up'\n payload: Payload\n req?: Partial<PayloadRequest>\n}): Promise<void> {\n const adapter = payload.db as unknown as MongooseAdapter\n const session = await getSession(adapter, req)\n const [from, to] = direction === 'up' ? ['sizes', 'variants'] : ['variants', 'sizes']\n\n const targets: {\n collection: Collection\n expectedVariantNames: string[]\n fromPath: string\n toPath: string\n }[] = []\n\n for (const collection of payload.config.collections) {\n if (!collection.upload) {\n continue\n }\n\n const upload = typeof collection.upload === 'object' ? collection.upload : undefined\n const expectedVariantNames = (upload?.variants ?? []).map(({ name }) => name)\n\n targets.push({\n collection: adapter.collections[collection.slug]!.collection,\n expectedVariantNames,\n fromPath: from,\n toPath: to,\n })\n\n if (collection.versions && adapter.versions[collection.slug]) {\n targets.push({\n collection: adapter.versions[collection.slug]!.collection,\n expectedVariantNames,\n fromPath: `version.${from}`,\n toPath: `version.${to}`,\n })\n }\n }\n\n for (const { collection, expectedVariantNames, fromPath, toPath } of targets) {\n const [sourceData, directCollision] = await Promise.all([\n collection.findOne({ [fromPath]: { $exists: true } }, { projection: { _id: 1 } }),\n collection.findOne(\n { [fromPath]: { $exists: true }, [toPath]: { $exists: true } },\n { projection: { _id: 1 } },\n ),\n ])\n\n if (\n sourceData &&\n (directCollision ||\n (await findUnexpectedDestinationData({ collection, expectedVariantNames, toPath })))\n ) {\n throw new Error(\n `Cannot run the sizes-to-variants migration because collection \"${collection.collectionName}\" contains both \"${fromPath}\" and \"${toPath}\" data. Move or rename the existing destination data before running this migration.`,\n )\n }\n }\n\n // Index changes can't be part of a multi-document transaction, and one made after the\n // migration's transaction has written to a collection aborts it. A transaction's snapshot starts\n // at its first operation, so re-keying every index before any transactional write is safe.\n for (const target of targets) {\n await rekeyIndexes(target)\n }\n\n for (const { collection, fromPath, toPath } of targets) {\n const result = await collection.updateMany(\n { [fromPath]: { $exists: true }, [toPath]: { $exists: false } },\n { $rename: { [fromPath]: toPath } },\n { session },\n )\n\n payload.logger.info({\n msg: `sizes-to-variants (${direction}): renamed ${fromPath} on ${result.modifiedCount} document(s) in \"${collection.collectionName}\"`,\n })\n }\n}\n\nasync function findUnexpectedDestinationData({\n collection,\n expectedVariantNames,\n toPath,\n}: {\n collection: Collection\n expectedVariantNames: string[]\n toPath: string\n}): Promise<Document | null> {\n const expectedVariantNameSet = new Set(expectedVariantNames)\n const cursor = collection.find(\n { [toPath]: { $exists: true } },\n { projection: { _id: 1, [toPath]: 1 } },\n )\n\n try {\n for await (const document of cursor) {\n const destinationData = getDocumentPath({ document, path: toPath })\n\n if (hasUnexpectedVariantData({ destinationData, expectedVariantNameSet })) {\n return document\n }\n }\n } finally {\n await cursor.close()\n }\n\n return null\n}\n\nfunction getDocumentPath({ document, path }: { document: Document; path: string }): unknown {\n return path.split('.').reduce<unknown>((value, pathSegment) => {\n if (!isRecord(value)) {\n return undefined\n }\n\n return value[pathSegment]\n }, document)\n}\n\nfunction hasUnexpectedVariantData({\n destinationData,\n expectedVariantNameSet,\n}: {\n destinationData: unknown\n expectedVariantNameSet: Set<string>\n}): boolean {\n if (!isRecord(destinationData)) {\n return destinationData !== null && destinationData !== undefined\n }\n\n for (const [variantName, variantData] of Object.entries(destinationData)) {\n if (!expectedVariantNameSet.has(variantName)) {\n return true\n }\n\n if (variantData === null || variantData === undefined) {\n continue\n }\n\n if (\n !isRecord(variantData) ||\n Object.keys(variantData).some(\n (metadataFieldName) => !GENERATED_VARIANT_METADATA_FIELDS.has(metadataFieldName),\n )\n ) {\n return true\n }\n }\n\n return false\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nasync function rekeyIndexes({\n collection,\n fromPath,\n toPath,\n}: {\n collection: Collection\n fromPath: string\n toPath: string\n}): Promise<void> {\n let indexes: IndexDescriptionInfo[]\n\n try {\n indexes = await collection.indexes()\n } catch (err) {\n if ((err as { code?: number }).code === NAMESPACE_NOT_FOUND_CODE) {\n return\n }\n\n throw err\n }\n\n for (const index of indexes) {\n const sourceKeys = getIndexKeysForCreate({ fromPath, index, toPath: fromPath })\n\n if (!Object.keys(sourceKeys).some((key) => isPathAtOrBelow({ key, path: fromPath }))) {\n continue\n }\n\n const rekeyedKeys = getIndexKeysForCreate({ fromPath, index, toPath })\n const destinationOptions = getDestinationIndexOptions({ fromPath, index, toPath })\n\n if (index.weights && '_fts' in index.key && '_ftsx' in index.key) {\n await rekeyTextIndex({\n collection,\n destinationOptions,\n index,\n rekeyedKeys,\n sourceKeys,\n })\n continue\n }\n\n try {\n await collection.createIndex(rekeyedKeys, destinationOptions)\n } catch (err) {\n if (!INDEX_CONFLICT_CODES.has((err as { code?: number }).code ?? 0)) {\n throw err\n }\n\n const destinationIndex = (await collection.indexes()).find((candidate) =>\n isDeepStrictEqual(\n getIndexKeysForCreate({ fromPath: toPath, index: candidate, toPath }),\n rekeyedKeys,\n ),\n )\n const existingDestinationOptions = destinationIndex\n ? getDestinationIndexOptions({\n fromPath: toPath,\n index: destinationIndex,\n toPath,\n })\n : undefined\n\n if (!destinationIndex || !isDeepStrictEqual(existingDestinationOptions, destinationOptions)) {\n throw err\n }\n }\n\n await collection.dropIndex(index.name!)\n }\n}\n\nasync function rekeyTextIndex({\n collection,\n destinationOptions,\n index,\n rekeyedKeys,\n sourceKeys,\n}: {\n collection: Collection\n destinationOptions: CreateIndexesOptions\n index: IndexDescriptionInfo\n rekeyedKeys: Record<string, IndexDirection>\n sourceKeys: Record<string, IndexDirection>\n}): Promise<void> {\n if (!index.name) {\n throw new Error('Cannot re-key an unnamed MongoDB text index.')\n }\n\n const sourceOptions: CreateIndexesOptions = {\n ...getDestinationIndexOptions({ fromPath: '', index, toPath: '' }),\n name: index.name,\n }\n\n await collection.dropIndex(index.name)\n\n try {\n await collection.createIndex(rekeyedKeys, destinationOptions)\n } catch (err) {\n try {\n await collection.createIndex(sourceKeys, sourceOptions)\n } catch (restoreErr) {\n throw new AggregateError(\n [err, restoreErr],\n `Failed to create the replacement for MongoDB text index \"${index.name}\" and failed to restore the source index.`,\n )\n }\n\n throw err\n }\n}\n\nfunction getIndexKeysForCreate({\n fromPath,\n index,\n toPath,\n}: {\n fromPath: string\n index: IndexDescriptionInfo\n toPath: string\n}): Record<string, IndexDirection> {\n const keys: [string, IndexDirection][] = []\n const hasInternalTextKeys = '_fts' in index.key && '_ftsx' in index.key\n\n for (const [key, value] of Object.entries(index.key)) {\n if (hasInternalTextKeys && key === '_fts') {\n for (const textPath of Object.keys(index.weights ?? {})) {\n keys.push([rekeyPath({ fromPath, path: textPath, toPath }), 'text'])\n }\n continue\n }\n\n if (hasInternalTextKeys && key === '_ftsx') {\n continue\n }\n\n keys.push([rekeyPath({ fromPath, path: key, toPath }), value])\n }\n\n return Object.fromEntries(keys)\n}\n\nfunction getDestinationIndexOptions({\n fromPath,\n index,\n toPath,\n}: {\n fromPath: string\n index: IndexDescriptionInfo\n toPath: string\n}): CreateIndexesOptions {\n const options: CreateIndexesOptions = {\n '2dsphereIndexVersion': index['2dsphereIndexVersion'],\n background: index.background,\n bits: index.bits,\n bucketSize: index.bucketSize,\n collation: index.collation,\n default_language: index.default_language,\n expireAfterSeconds: index.expireAfterSeconds,\n hidden: index.hidden,\n language_override: index.language_override,\n max: index.max,\n min: index.min,\n partialFilterExpression: index.partialFilterExpression\n ? rekeyDocumentPaths({ document: index.partialFilterExpression, fromPath, toPath })\n : undefined,\n sparse: index.sparse,\n storageEngine: index.storageEngine,\n textIndexVersion: index.textIndexVersion,\n unique: index.unique,\n weights: index.weights\n ? rekeyDocumentPaths({ document: index.weights, fromPath, toPath })\n : undefined,\n wildcardProjection: index.wildcardProjection\n ? rekeyDocumentPaths({ document: index.wildcardProjection, fromPath, toPath })\n : undefined,\n }\n\n return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined))\n}\n\nfunction rekeyDocumentPaths({\n document,\n fromPath,\n toPath,\n}: {\n document: Document\n fromPath: string\n toPath: string\n}): Document {\n return Object.fromEntries(\n Object.entries(document).map(([key, value]) => [\n rekeyPath({ fromPath, path: key, toPath }),\n rekeyDocumentValue({ fromPath, toPath, value }),\n ]),\n )\n}\n\nfunction isPathAtOrBelow({ key, path }: { key: string; path: string }): boolean {\n return key === path || key.startsWith(`${path}.`)\n}\n\nfunction rekeyPath({\n fromPath,\n path,\n toPath,\n}: {\n fromPath: string\n path: string\n toPath: string\n}): string {\n return isPathAtOrBelow({ key: path, path: fromPath })\n ? `${toPath}${path.slice(fromPath.length)}`\n : path\n}\n\nfunction rekeyDocumentValue({\n fromPath,\n toPath,\n value,\n}: {\n fromPath: string\n toPath: string\n value: unknown\n}): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => rekeyDocumentValue({ fromPath, toPath, value: item }))\n }\n\n if (\n value !== null &&\n typeof value === 'object' &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)\n ) {\n return rekeyDocumentPaths({ document: value, fromPath, toPath })\n }\n\n return value\n}\n"],"names":["isDeepStrictEqual","getSession","INDEX_CONFLICT_CODES","Set","NAMESPACE_NOT_FOUND_CODE","GENERATED_VARIANT_METADATA_FIELDS","migrateSizesToVariants","direction","payload","req","adapter","db","session","from","to","targets","collection","config","collections","upload","undefined","expectedVariantNames","variants","map","name","push","slug","fromPath","toPath","versions","sourceData","directCollision","Promise","all","findOne","$exists","projection","_id","findUnexpectedDestinationData","Error","collectionName","target","rekeyIndexes","result","updateMany","$rename","logger","info","msg","modifiedCount","expectedVariantNameSet","cursor","find","document","destinationData","getDocumentPath","path","hasUnexpectedVariantData","close","split","reduce","value","pathSegment","isRecord","variantName","variantData","Object","entries","has","keys","some","metadataFieldName","Array","isArray","indexes","err","code","index","sourceKeys","getIndexKeysForCreate","key","isPathAtOrBelow","rekeyedKeys","destinationOptions","getDestinationIndexOptions","weights","rekeyTextIndex","createIndex","destinationIndex","candidate","existingDestinationOptions","dropIndex","sourceOptions","restoreErr","AggregateError","hasInternalTextKeys","textPath","rekeyPath","fromEntries","options","background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","rekeyDocumentPaths","sparse","storageEngine","textIndexVersion","unique","wildcardProjection","filter","rekeyDocumentValue","startsWith","slice","length","item","getPrototypeOf","prototype"],"mappings":"AASA,SAASA,iBAAiB,QAAQ,YAAW;AAI7C,SAASC,UAAU,QAAQ,6BAA4B;AAEvD,0EAA0E,GAC1E,MAAMC,uBAAuB,IAAIC,IAAI;IAAC;IAAI;CAAG;AAC7C,oEAAoE,GACpE,MAAMC,2BAA2B;AACjC,MAAMC,oCAAoC,IAAIF,IAAI;IAChD;IACA;IACA;IACA;IACA;IACA;CACD;AAED;;;;;CAKC,GACD,OAAO,eAAeG,uBAAuB,EAC3CC,YAAY,IAAI,EAChBC,OAAO,EACPC,GAAG,EAKJ;IACC,MAAMC,UAAUF,QAAQG,EAAE;IAC1B,MAAMC,UAAU,MAAMX,WAAWS,SAASD;IAC1C,MAAM,CAACI,MAAMC,GAAG,GAAGP,cAAc,OAAO;QAAC;QAAS;KAAW,GAAG;QAAC;QAAY;KAAQ;IAErF,MAAMQ,UAKA,EAAE;IAER,KAAK,MAAMC,cAAcR,QAAQS,MAAM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CAAC,EAAE,SAAS,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IAEjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,uCAAuC;IACvC,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED,eAAO,MAAM,oBAAoB,mGAS9B,wBAAwB,KAAG,OAAO,CAAC,aAAa,EAAE,CA0cpD,CAAA"}
1
+ {"version":3,"file":"buildJoinAggregation.d.ts","sourceRoot":"","sources":["../../src/utilities/buildJoinAggregation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAE7C,OAAO,EAIL,KAAK,cAAc,EAInB,KAAK,SAAS,EACd,KAAK,yBAAyB,EAC/B,MAAM,SAAS,CAAA;AAGhB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAOlD,KAAK,wBAAwB,GAAG;IAC9B,OAAO,EAAE,eAAe,CAAA;IACxB,UAAU,EAAE,cAAc,CAAA;IAC1B,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,KAAK,CAAC,EAAE,SAAS,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IAEjC,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC/B,uCAAuC;IACvC,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB,CAAA;AAED,eAAO,MAAM,oBAAoB,mGAS9B,wBAAwB,KAAG,OAAO,CAAC,aAAa,EAAE,CAgdpD,CAAA"}
@@ -104,10 +104,12 @@ export const buildJoinAggregation = async ({ adapter, collection, collectionConf
104
104
  [sortProperty]: sortDirection
105
105
  }
106
106
  },
107
- {
108
- // Unfortunately, we can't use $skip here because we can lose data, instead we do $slice then
109
- $limit: page ? page * limitJoin : limitJoin
110
- },
107
+ ...limitJoin > 0 ? [
108
+ {
109
+ // Unfortunately, we can't use $skip here because we can lose data, instead we do $slice then
110
+ $limit: page ? page * limitJoin : limitJoin
111
+ }
112
+ ] : [],
111
113
  {
112
114
  $project: {
113
115
  value: '$_id',
@@ -191,16 +193,18 @@ export const buildJoinAggregation = async ({ adapter, collection, collectionConf
191
193
  }
192
194
  }
193
195
  });
194
- aggregate.push({
195
- $set: {
196
- [`${as}.docs`]: {
197
- $slice: [
198
- `$${as}.docs`,
199
- ...sliceValue
200
- ]
196
+ if (limitJoin > 0) {
197
+ aggregate.push({
198
+ $set: {
199
+ [`${as}.docs`]: {
200
+ $slice: [
201
+ `$${as}.docs`,
202
+ ...sliceValue
203
+ ]
204
+ }
201
205
  }
202
- }
203
- });
206
+ });
207
+ }
204
208
  }
205
209
  for (const slug of Object.keys(joinConfig)){
206
210
  const joinsList = joinConfig[slug];
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/buildJoinAggregation.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\n\nimport {\n APIError,\n appendVersionToQueryKey,\n buildVersionCollectionFields,\n type CollectionSlug,\n combineQueries,\n type FlattenedField,\n getQueryDraftsSort,\n type JoinQuery,\n type SanitizedCollectionConfig,\n} from 'payload'\nimport { fieldShouldBeLocalized, hasDraftsEnabled } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\nimport type { CollectionModel } from '../types.js'\n\nimport { buildQuery } from '../queries/buildQuery.js'\nimport { buildSortParam } from '../queries/buildSortParam.js'\nimport { getCollection } from './getEntity.js'\n\ntype BuildJoinAggregationArgs = {\n adapter: MongooseAdapter\n collection: CollectionSlug\n collectionConfig: SanitizedCollectionConfig\n draftsEnabled?: boolean\n joins?: JoinQuery\n locale?: string\n projection?: Record<string, true>\n // the where clause for the top collection\n query?: Record<string, unknown>\n /** whether the query is from drafts */\n versions?: boolean\n}\n\nexport const buildJoinAggregation = async ({\n adapter,\n collection,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection,\n versions,\n}: BuildJoinAggregationArgs): Promise<PipelineStage[]> => {\n if (!adapter.useJoinAggregations) {\n return []\n }\n if (\n (Object.keys(collectionConfig.joins).length === 0 &&\n collectionConfig.polymorphicJoins.length == 0) ||\n joins === false\n ) {\n return []\n }\n\n const joinConfig = adapter.payload.collections[collection]?.config?.joins\n\n if (!joinConfig) {\n throw new APIError(`Could not retrieve sanitized join config for ${collection}.`)\n }\n\n const aggregate: PipelineStage[] = []\n const polymorphicJoinsConfig = adapter.payload.collections[collection]?.config?.polymorphicJoins\n\n if (!polymorphicJoinsConfig) {\n throw new APIError(`Could not retrieve sanitized polymorphic joins config for ${collection}.`)\n }\n\n for (const join of polymorphicJoinsConfig) {\n if (projection && !projection[join.joinPath]) {\n continue\n }\n\n if (joins?.[join.joinPath] === false) {\n continue\n }\n\n const {\n count = false,\n limit: limitJoin = join.field.defaultLimit ?? 10,\n page,\n sort: sortJoin = join.field.defaultSort || collectionConfig.defaultSort,\n where: whereJoin = {},\n } = joins?.[join.joinPath] || {}\n\n const aggregatedFields: FlattenedField[] = []\n for (const collectionSlug of join.field.collection) {\n const { collectionConfig } = getCollection({ adapter, collectionSlug })\n\n for (const field of collectionConfig.flattenedFields) {\n if (!aggregatedFields.some((eachField) => eachField.name === field.name)) {\n aggregatedFields.push(field)\n }\n }\n }\n\n const sort = buildSortParam({\n adapter,\n config: adapter.payload.config,\n fields: aggregatedFields,\n locale,\n sort: sortJoin,\n timestamps: true,\n })\n\n const $match = await buildQuery({\n adapter,\n fields: aggregatedFields,\n locale,\n where: whereJoin,\n })\n\n const sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const projectSort = sortProperty !== '_id' && sortProperty !== 'relationTo'\n\n const aliases: string[] = []\n\n const as = join.joinPath\n\n for (const collectionSlug of join.field.collection) {\n const alias = `${as}.docs.${collectionSlug}`\n aliases.push(alias)\n\n const basePipeline = [\n {\n $addFields: {\n relationTo: {\n $literal: collectionSlug,\n },\n },\n },\n {\n $match: {\n $and: [\n {\n $expr: {\n $eq: [`$${join.field.on}`, '$$root_id_'],\n },\n },\n $match,\n ],\n },\n },\n ]\n\n const { Model: JoinModel } = getCollection({ adapter, collectionSlug })\n\n aggregate.push({\n $lookup: {\n as: alias,\n from: JoinModel.collection.name,\n let: {\n root_id_: '$_id',\n },\n pipeline: [\n ...basePipeline,\n {\n $sort: {\n [sortProperty]: sortDirection,\n },\n },\n {\n // Unfortunately, we can't use $skip here because we can lose data, instead we do $slice then\n $limit: page ? page * limitJoin : limitJoin,\n },\n {\n $project: {\n value: '$_id',\n ...(projectSort && {\n [sortProperty]: 1,\n }),\n relationTo: 1,\n },\n },\n ],\n },\n })\n\n if (count) {\n aggregate.push({\n $lookup: {\n as: `${as}.totalDocs.${alias}`,\n from: JoinModel.collection.name,\n let: {\n root_id_: '$_id',\n },\n pipeline: [\n ...basePipeline,\n {\n $count: 'result',\n },\n ],\n },\n })\n }\n }\n\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $concatArrays: aliases.map((alias) => `$${alias}`),\n },\n },\n })\n\n if (count) {\n aggregate.push({\n $addFields: {\n [`${as}.totalDocs`]: {\n $add: aliases.map((alias) => ({\n $ifNull: [\n {\n $first: `$${as}.totalDocs.${alias}.result`,\n },\n 0,\n ],\n })),\n },\n },\n })\n }\n\n aggregate.push({\n $set: {\n [`${as}.docs`]: {\n $sortArray: {\n input: `$${as}.docs`,\n sortBy: {\n [sortProperty]: sortDirection,\n },\n },\n },\n },\n })\n\n const sliceValue = page ? [(page - 1) * limitJoin, limitJoin] : [limitJoin]\n\n aggregate.push({\n $addFields: {\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n },\n },\n })\n\n aggregate.push({\n $set: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, ...sliceValue],\n },\n },\n })\n }\n\n for (const slug of Object.keys(joinConfig)) {\n const joinsList = joinConfig[slug]\n\n if (!joinsList) {\n throw new APIError(`Failed to retrieve array of joins for ${slug} in collectio ${collection}`)\n }\n\n for (const join of joinsList) {\n const projectionPath = versions ? `version.${join.joinPath}` : join.joinPath\n if (projection && !projection[projectionPath]) {\n continue\n }\n\n if (joins?.[join.joinPath] === false) {\n continue\n }\n\n const collectionConfig = adapter.payload.collections[join.field.collection as string]?.config\n\n if (!collectionConfig) {\n throw new APIError(\n `Collection config for ${join.field.collection.toString()} was not found`,\n )\n }\n\n let JoinModel: CollectionModel | undefined\n\n const useDrafts = (draftsEnabled || versions) && hasDraftsEnabled(collectionConfig)\n\n if (useDrafts) {\n JoinModel = adapter.versions[collectionConfig.slug]\n } else {\n JoinModel = adapter.collections[collectionConfig.slug]\n }\n\n if (!JoinModel) {\n throw new APIError(`Join Model was not found for ${collectionConfig.slug}`)\n }\n\n const {\n count,\n limit: limitJoin = join.field.defaultLimit ?? 10,\n page,\n sort: sortJoin = join.field.defaultSort || collectionConfig.defaultSort,\n where: whereJoin = {},\n } = joins?.[join.joinPath] || {}\n\n if (Array.isArray(join.field.collection)) {\n throw new Error('Unreachable')\n }\n\n const fields = useDrafts\n ? buildVersionCollectionFields(adapter.payload.config, collectionConfig, true)\n : collectionConfig.flattenedFields\n\n const sort = buildSortParam({\n adapter,\n config: adapter.payload.config,\n fields,\n locale,\n sort: useDrafts ? getQueryDraftsSort({ collectionConfig, sort: sortJoin }) : sortJoin,\n timestamps: true,\n })\n const sortProperty = Object.keys(sort)[0]!\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const $match = await JoinModel.buildQuery({\n locale,\n payload: adapter.payload,\n where: useDrafts\n ? combineQueries(appendVersionToQueryKey(whereJoin), {\n latest: {\n equals: true,\n },\n })\n : whereJoin,\n })\n\n const pipeline: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out>[] = [\n { $match },\n {\n $sort: { [sortProperty]: sortDirection },\n },\n ]\n\n if (page) {\n pipeline.push({\n $skip: (page - 1) * limitJoin,\n })\n }\n\n if (limitJoin > 0) {\n pipeline.push({\n $limit: limitJoin + 1,\n })\n }\n\n let polymorphicSuffix = ''\n if (Array.isArray(join.targetField.relationTo)) {\n polymorphicSuffix = '.value'\n }\n\n const addTotalDocsAggregation = (as: string, foreignField: string) =>\n aggregate.push(\n {\n $lookup: {\n as: `${as}.totalDocs`,\n foreignField,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline: [\n {\n $match,\n },\n {\n $count: 'result',\n },\n ],\n },\n },\n {\n $addFields: {\n [`${as}.totalDocs`]: { $ifNull: [{ $first: `$${as}.totalDocs.result` }, 0] },\n },\n },\n )\n\n let foreignFieldPrefix = ''\n\n if (useDrafts) {\n foreignFieldPrefix = 'version.'\n }\n\n if (adapter.payload.config.localization && locale === 'all') {\n adapter.payload.config.localization.localeCodes.forEach((code) => {\n const as = `${versions ? `version.${join.joinPath}` : join.joinPath}${code}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${foreignFieldPrefix}${join.field.on}${code}${polymorphicSuffix}`,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: useDrafts ? `$$doc.parent` : '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: limitJoin\n ? { $gt: [{ $size: `$${as}.docs` }, limitJoin] }\n : false,\n // Boolean indicating if more docs than limit\n },\n },\n )\n\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n\n if (count) {\n addTotalDocsAggregation(\n as,\n `${foreignFieldPrefix}${join.field.on}${code}${polymorphicSuffix}`,\n )\n }\n })\n } else {\n const localeSuffix =\n fieldShouldBeLocalized({\n field: join.field,\n parentIsLocalized: join.parentIsLocalized,\n }) &&\n adapter.payload.config.localization &&\n locale\n ? `.${locale}`\n : ''\n const as = `${versions ? `version.${join.joinPath}` : join.joinPath}${localeSuffix}`\n\n let foreignField: string\n\n if (join.getForeignPath) {\n foreignField = `${join.getForeignPath({ locale })}${polymorphicSuffix}`\n } else {\n foreignField = `${join.field.on}${polymorphicSuffix}`\n }\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${foreignFieldPrefix}${foreignField}`,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: useDrafts ? `$$doc.parent` : '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n }, // Boolean indicating if more docs than limit\n },\n },\n )\n\n if (count) {\n addTotalDocsAggregation(as, `${foreignFieldPrefix}${foreignField}`)\n }\n\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n }\n }\n }\n\n return aggregate\n}\n"],"names":["APIError","appendVersionToQueryKey","buildVersionCollectionFields","combineQueries","getQueryDraftsSort","fieldShouldBeLocalized","hasDraftsEnabled","buildQuery","buildSortParam","getCollection","buildJoinAggregation","adapter","collection","collectionConfig","draftsEnabled","joins","locale","projection","versions","useJoinAggregations","Object","keys","length","polymorphicJoins","joinConfig","payload","collections","config","aggregate","polymorphicJoinsConfig","join","joinPath","count","limit","limitJoin","field","defaultLimit","page","sort","sortJoin","defaultSort","where","whereJoin","aggregatedFields","collectionSlug","flattenedFields","some","eachField","name","push","fields","timestamps","$match","sortProperty","sortDirection","projectSort","aliases","as","alias","basePipeline","$addFields","relationTo","$literal","$and","$expr","$eq","on","Model","JoinModel","$lookup","from","let","root_id_","pipeline","$sort","$limit","$project","value","$count","$concatArrays","map","$add","$ifNull","$first","$set","$sortArray","input","sortBy","sliceValue","$gt","$size","Number","MAX_VALUE","$slice","slug","joinsList","projectionPath","toString","useDrafts","Array","isArray","Error","latest","equals","$skip","polymorphicSuffix","targetField","addTotalDocsAggregation","foreignField","localField","foreignFieldPrefix","localization","localeCodes","forEach","code","$map","in","localeSuffix","parentIsLocalized","getForeignPath"],"mappings":"AAEA,SACEA,QAAQ,EACRC,uBAAuB,EACvBC,4BAA4B,EAE5BC,cAAc,EAEdC,kBAAkB,QAGb,UAAS;AAChB,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,iBAAgB;AAKzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,aAAa,QAAQ,iBAAgB;AAgB9C,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,aAAa,EACbC,KAAK,EACLC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACiB;IACzB,IAAI,CAACP,QAAQQ,mBAAmB,EAAE;QAChC,OAAO,EAAE;IACX;IACA,IACE,AAACC,OAAOC,IAAI,CAACR,iBAAiBE,KAAK,EAAEO,MAAM,KAAK,KAC9CT,iBAAiBU,gBAAgB,CAACD,MAAM,IAAI,KAC9CP,UAAU,OACV;QACA,OAAO,EAAE;IACX;IAEA,MAAMS,aAAab,QAAQc,OAAO,CAACC,WAAW,CAACd,WAAW,EAAEe,QAAQZ;IAEpE,IAAI,CAACS,YAAY;QACf,MAAM,IAAIxB,SAAS,CAAC,6CAA6C,EAAEY,WAAW,CAAC,CAAC;IAClF;IAEA,MAAMgB,YAA6B,EAAE;IACrC,MAAMC,yBAAyBlB,QAAQc,OAAO,CAACC,WAAW,CAACd,WAA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ACvD;gBAEA7E,UAAUqB,IAAI,CACZ;oBACEoB,SAAS;wBACPZ,IAAI,GAAGA,GAAG,KAAK,CAAC;wBAChBmD,cAAc,GAAGE,qBAAqBF,cAAc;wBACpDtC,MAAMF,UAAUxD,UAAU,CAACoC,IAAI;wBAC/B6D,YAAY3F,WAAW,WAAW;wBAClCuD;oBACF;gBACF,GACA;oBACEb,YAAY;wBACV,CAAC,GAAGH,GAAG,KAAK,CAAC,CAAC,EAAE;4BACd0D,MAAM;gCACJ1D,IAAI;gCACJ2D,IAAIlB,YAAY,CAAC,YAAY,CAAC,GAAG;gCACjCZ,OAAO,CAAC,CAAC,EAAE7B,GAAG,KAAK,CAAC;4BACtB;wBACF;wBACA,CAAC,GAAGA,GAAG,YAAY,CAAC,CAAC,EAAE;4BACrBgC,KAAK;gCAAC;oCAAEC,OAAO,CAAC,CAAC,EAAEjC,GAAG,KAAK,CAAC;gCAAC;gCAAGvB,aAAayD,OAAOC,SAAS;6BAAC;wBAChE;oBACF;gBACF;gBAGF,IAAI5D,OAAO;oBACT2E,wBAAwBlD,IAAI,GAAGqD,qBAAqBF,cAAc;gBACpE;gBAEA,IAAI1E,YAAY,GAAG;oBACjBN,UAAUqB,IAAI,CAAC;wBACbW,YAAY;4BACV,CAAC,GAAGH,GAAG,KAAK,CAAC,CAAC,EAAE;gCACdoC,QAAQ;oCAAC,CAAC,CAAC,EAAEpC,GAAG,KAAK,CAAC;oCAAEvB;iCAAU;4BACpC;wBACF;oBACF;gBACF;YACF;QACF;IACF;IAEA,OAAON;AACT,EAAC"}
1
+ {"version":3,"sources":["../../src/utilities/buildJoinAggregation.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\n\nimport {\n APIError,\n appendVersionToQueryKey,\n buildVersionCollectionFields,\n type CollectionSlug,\n combineQueries,\n type FlattenedField,\n getQueryDraftsSort,\n type JoinQuery,\n type SanitizedCollectionConfig,\n} from 'payload'\nimport { fieldShouldBeLocalized, hasDraftsEnabled } from 'payload/shared'\n\nimport type { MongooseAdapter } from '../index.js'\nimport type { CollectionModel } from '../types.js'\n\nimport { buildQuery } from '../queries/buildQuery.js'\nimport { buildSortParam } from '../queries/buildSortParam.js'\nimport { getCollection } from './getEntity.js'\n\ntype BuildJoinAggregationArgs = {\n adapter: MongooseAdapter\n collection: CollectionSlug\n collectionConfig: SanitizedCollectionConfig\n draftsEnabled?: boolean\n joins?: JoinQuery\n locale?: string\n projection?: Record<string, true>\n // the where clause for the top collection\n query?: Record<string, unknown>\n /** whether the query is from drafts */\n versions?: boolean\n}\n\nexport const buildJoinAggregation = async ({\n adapter,\n collection,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection,\n versions,\n}: BuildJoinAggregationArgs): Promise<PipelineStage[]> => {\n if (!adapter.useJoinAggregations) {\n return []\n }\n if (\n (Object.keys(collectionConfig.joins).length === 0 &&\n collectionConfig.polymorphicJoins.length == 0) ||\n joins === false\n ) {\n return []\n }\n\n const joinConfig = adapter.payload.collections[collection]?.config?.joins\n\n if (!joinConfig) {\n throw new APIError(`Could not retrieve sanitized join config for ${collection}.`)\n }\n\n const aggregate: PipelineStage[] = []\n const polymorphicJoinsConfig = adapter.payload.collections[collection]?.config?.polymorphicJoins\n\n if (!polymorphicJoinsConfig) {\n throw new APIError(`Could not retrieve sanitized polymorphic joins config for ${collection}.`)\n }\n\n for (const join of polymorphicJoinsConfig) {\n if (projection && !projection[join.joinPath]) {\n continue\n }\n\n if (joins?.[join.joinPath] === false) {\n continue\n }\n\n const {\n count = false,\n limit: limitJoin = join.field.defaultLimit ?? 10,\n page,\n sort: sortJoin = join.field.defaultSort || collectionConfig.defaultSort,\n where: whereJoin = {},\n } = joins?.[join.joinPath] || {}\n\n const aggregatedFields: FlattenedField[] = []\n for (const collectionSlug of join.field.collection) {\n const { collectionConfig } = getCollection({ adapter, collectionSlug })\n\n for (const field of collectionConfig.flattenedFields) {\n if (!aggregatedFields.some((eachField) => eachField.name === field.name)) {\n aggregatedFields.push(field)\n }\n }\n }\n\n const sort = buildSortParam({\n adapter,\n config: adapter.payload.config,\n fields: aggregatedFields,\n locale,\n sort: sortJoin,\n timestamps: true,\n })\n\n const $match = await buildQuery({\n adapter,\n fields: aggregatedFields,\n locale,\n where: whereJoin,\n })\n\n const sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const projectSort = sortProperty !== '_id' && sortProperty !== 'relationTo'\n\n const aliases: string[] = []\n\n const as = join.joinPath\n\n for (const collectionSlug of join.field.collection) {\n const alias = `${as}.docs.${collectionSlug}`\n aliases.push(alias)\n\n const basePipeline = [\n {\n $addFields: {\n relationTo: {\n $literal: collectionSlug,\n },\n },\n },\n {\n $match: {\n $and: [\n {\n $expr: {\n $eq: [`$${join.field.on}`, '$$root_id_'],\n },\n },\n $match,\n ],\n },\n },\n ]\n\n const { Model: JoinModel } = getCollection({ adapter, collectionSlug })\n\n aggregate.push({\n $lookup: {\n as: alias,\n from: JoinModel.collection.name,\n let: {\n root_id_: '$_id',\n },\n pipeline: [\n ...basePipeline,\n {\n $sort: {\n [sortProperty]: sortDirection,\n },\n },\n ...(limitJoin > 0\n ? [\n {\n // Unfortunately, we can't use $skip here because we can lose data, instead we do $slice then\n $limit: page ? page * limitJoin : limitJoin,\n },\n ]\n : []),\n {\n $project: {\n value: '$_id',\n ...(projectSort && {\n [sortProperty]: 1,\n }),\n relationTo: 1,\n },\n },\n ],\n },\n })\n\n if (count) {\n aggregate.push({\n $lookup: {\n as: `${as}.totalDocs.${alias}`,\n from: JoinModel.collection.name,\n let: {\n root_id_: '$_id',\n },\n pipeline: [\n ...basePipeline,\n {\n $count: 'result',\n },\n ],\n },\n })\n }\n }\n\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $concatArrays: aliases.map((alias) => `$${alias}`),\n },\n },\n })\n\n if (count) {\n aggregate.push({\n $addFields: {\n [`${as}.totalDocs`]: {\n $add: aliases.map((alias) => ({\n $ifNull: [\n {\n $first: `$${as}.totalDocs.${alias}.result`,\n },\n 0,\n ],\n })),\n },\n },\n })\n }\n\n aggregate.push({\n $set: {\n [`${as}.docs`]: {\n $sortArray: {\n input: `$${as}.docs`,\n sortBy: {\n [sortProperty]: sortDirection,\n },\n },\n },\n },\n })\n\n const sliceValue = page ? [(page - 1) * limitJoin, limitJoin] : [limitJoin]\n\n aggregate.push({\n $addFields: {\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n },\n },\n })\n\n if (limitJoin > 0) {\n aggregate.push({\n $set: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, ...sliceValue],\n },\n },\n })\n }\n }\n\n for (const slug of Object.keys(joinConfig)) {\n const joinsList = joinConfig[slug]\n\n if (!joinsList) {\n throw new APIError(`Failed to retrieve array of joins for ${slug} in collectio ${collection}`)\n }\n\n for (const join of joinsList) {\n const projectionPath = versions ? `version.${join.joinPath}` : join.joinPath\n if (projection && !projection[projectionPath]) {\n continue\n }\n\n if (joins?.[join.joinPath] === false) {\n continue\n }\n\n const collectionConfig = adapter.payload.collections[join.field.collection as string]?.config\n\n if (!collectionConfig) {\n throw new APIError(\n `Collection config for ${join.field.collection.toString()} was not found`,\n )\n }\n\n let JoinModel: CollectionModel | undefined\n\n const useDrafts = (draftsEnabled || versions) && hasDraftsEnabled(collectionConfig)\n\n if (useDrafts) {\n JoinModel = adapter.versions[collectionConfig.slug]\n } else {\n JoinModel = adapter.collections[collectionConfig.slug]\n }\n\n if (!JoinModel) {\n throw new APIError(`Join Model was not found for ${collectionConfig.slug}`)\n }\n\n const {\n count,\n limit: limitJoin = join.field.defaultLimit ?? 10,\n page,\n sort: sortJoin = join.field.defaultSort || collectionConfig.defaultSort,\n where: whereJoin = {},\n } = joins?.[join.joinPath] || {}\n\n if (Array.isArray(join.field.collection)) {\n throw new Error('Unreachable')\n }\n\n const fields = useDrafts\n ? buildVersionCollectionFields(adapter.payload.config, collectionConfig, true)\n : collectionConfig.flattenedFields\n\n const sort = buildSortParam({\n adapter,\n config: adapter.payload.config,\n fields,\n locale,\n sort: useDrafts ? getQueryDraftsSort({ collectionConfig, sort: sortJoin }) : sortJoin,\n timestamps: true,\n })\n const sortProperty = Object.keys(sort)[0]!\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n const $match = await JoinModel.buildQuery({\n locale,\n payload: adapter.payload,\n where: useDrafts\n ? combineQueries(appendVersionToQueryKey(whereJoin), {\n latest: {\n equals: true,\n },\n })\n : whereJoin,\n })\n\n const pipeline: Exclude<PipelineStage, PipelineStage.Merge | PipelineStage.Out>[] = [\n { $match },\n {\n $sort: { [sortProperty]: sortDirection },\n },\n ]\n\n if (page) {\n pipeline.push({\n $skip: (page - 1) * limitJoin,\n })\n }\n\n if (limitJoin > 0) {\n pipeline.push({\n $limit: limitJoin + 1,\n })\n }\n\n let polymorphicSuffix = ''\n if (Array.isArray(join.targetField.relationTo)) {\n polymorphicSuffix = '.value'\n }\n\n const addTotalDocsAggregation = (as: string, foreignField: string) =>\n aggregate.push(\n {\n $lookup: {\n as: `${as}.totalDocs`,\n foreignField,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline: [\n {\n $match,\n },\n {\n $count: 'result',\n },\n ],\n },\n },\n {\n $addFields: {\n [`${as}.totalDocs`]: { $ifNull: [{ $first: `$${as}.totalDocs.result` }, 0] },\n },\n },\n )\n\n let foreignFieldPrefix = ''\n\n if (useDrafts) {\n foreignFieldPrefix = 'version.'\n }\n\n if (adapter.payload.config.localization && locale === 'all') {\n adapter.payload.config.localization.localeCodes.forEach((code) => {\n const as = `${versions ? `version.${join.joinPath}` : join.joinPath}${code}`\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${foreignFieldPrefix}${join.field.on}${code}${polymorphicSuffix}`,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: useDrafts ? `$$doc.parent` : '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: limitJoin\n ? { $gt: [{ $size: `$${as}.docs` }, limitJoin] }\n : false,\n // Boolean indicating if more docs than limit\n },\n },\n )\n\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n\n if (count) {\n addTotalDocsAggregation(\n as,\n `${foreignFieldPrefix}${join.field.on}${code}${polymorphicSuffix}`,\n )\n }\n })\n } else {\n const localeSuffix =\n fieldShouldBeLocalized({\n field: join.field,\n parentIsLocalized: join.parentIsLocalized,\n }) &&\n adapter.payload.config.localization &&\n locale\n ? `.${locale}`\n : ''\n const as = `${versions ? `version.${join.joinPath}` : join.joinPath}${localeSuffix}`\n\n let foreignField: string\n\n if (join.getForeignPath) {\n foreignField = `${join.getForeignPath({ locale })}${polymorphicSuffix}`\n } else {\n foreignField = `${join.field.on}${polymorphicSuffix}`\n }\n\n aggregate.push(\n {\n $lookup: {\n as: `${as}.docs`,\n foreignField: `${foreignFieldPrefix}${foreignField}`,\n from: JoinModel.collection.name,\n localField: versions ? 'parent' : '_id',\n pipeline,\n },\n },\n {\n $addFields: {\n [`${as}.docs`]: {\n $map: {\n as: 'doc',\n in: useDrafts ? `$$doc.parent` : '$$doc._id',\n input: `$${as}.docs`,\n },\n }, // Slicing the docs to match the limit\n [`${as}.hasNextPage`]: {\n $gt: [{ $size: `$${as}.docs` }, limitJoin || Number.MAX_VALUE],\n }, // Boolean indicating if more docs than limit\n },\n },\n )\n\n if (count) {\n addTotalDocsAggregation(as, `${foreignFieldPrefix}${foreignField}`)\n }\n\n if (limitJoin > 0) {\n aggregate.push({\n $addFields: {\n [`${as}.docs`]: {\n $slice: [`$${as}.docs`, limitJoin],\n },\n },\n })\n }\n }\n }\n }\n\n return aggregate\n}\n"],"names":["APIError","appendVersionToQueryKey","buildVersionCollectionFields","combineQueries","getQueryDraftsSort","fieldShouldBeLocalized","hasDraftsEnabled","buildQuery","buildSortParam","getCollection","buildJoinAggregation","adapter","collection","collectionConfig","draftsEnabled","joins","locale","projection","versions","useJoinAggregations","Object","keys","length","polymorphicJoins","joinConfig","payload","collections","config","aggregate","polymorphicJoinsConfig","join","joinPath","count","limit","limitJoin","field","defaultLimit","page","sort","sortJoin","defaultSort","where","whereJoin","aggregatedFields","collectionSlug","flattenedFields","some","eachField","name","push","fields","timestamps","$match","sortProperty","sortDirection","projectSort","aliases","as","alias","basePipeline","$addFields","relationTo","$literal","$and","$expr","$eq","on","Model","JoinModel","$lookup","from","let","root_id_","pipeline","$sort","$limit","$project","value","$count","$concatArrays","map","$add","$ifNull","$first","$set","$sortArray","input","sortBy","sliceValue","$gt","$size","Number","MAX_VALUE","$slice","slug","joinsList","projectionPath","toString","useDrafts","Array","isArray","Error","latest","equals","$skip","polymorphicSuffix","targetField","addTotalDocsAggregation","foreignField","localField","foreignFieldPrefix","localization","localeCodes","forEach","code","$map","in","localeSuffix","parentIsLocalized","getForeignPath"],"mappings":"AAEA,SACEA,QAAQ,EACRC,uBAAuB,EACvBC,4BAA4B,EAE5BC,cAAc,EAEdC,kBAAkB,QAGb,UAAS;AAChB,SAASC,sBAAsB,EAAEC,gBAAgB,QAAQ,iBAAgB;AAKzE,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,cAAc,QAAQ,+BAA8B;AAC7D,SAASC,aAAa,QAAQ,iBAAgB;AAgB9C,OAAO,MAAMC,uBAAuB,OAAO,EACzCC,OAAO,EACPC,UAAU,EACVC,gBAAgB,EAChBC,aAAa,EACbC,KAAK,EACLC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACiB;IACzB,IAAI,CAACP,QAAQQ,mBAAmB,EAAE;QAChC,OAAO,EAAE;IACX;IACA,IACE,AAACC,OAAOC,IAAI,CAACR,iBAAiBE,KAAK,EAAEO,MAAM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AC,EAAE;gCACdoC,QAAQ;oCAAC,CAAC,CAAC,EAAEpC,GAAG,KAAK,CAAC;oCAAEvB;iCAAU;4BACpC;wBACF;oBACF;gBACF;YACF;QACF;IACF;IAEA,OAAON;AACT,EAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/db-mongodb",
3
- "version": "4.0.0-beta.3",
3
+ "version": "4.0.0-beta.5",
4
4
  "description": "The officially supported MongoDB database adapter for Payload",
5
5
  "homepage": "https://payloadcms.com",
6
6
  "license": "MIT",
@@ -53,19 +53,16 @@
53
53
  "@types/prompts": "^2.4.5",
54
54
  "mongodb": "7.5.0",
55
55
  "mongodb-memory-server": "10.1.4",
56
- "@payloadcms/eslint-config": "3.28.0",
57
- "payload": "4.0.0-beta.3"
56
+ "payload": "4.0.0-beta.5"
58
57
  },
59
58
  "peerDependencies": {
60
- "payload": "4.0.0-beta.3"
59
+ "payload": "4.0.0-beta.5"
61
60
  },
62
61
  "scripts": {
63
62
  "build": "pnpm build:types && pnpm build:swc",
64
63
  "build:debug": "pnpm build",
65
64
  "build:swc": "swc ./src -d ./dist --config-file .swcrc-build --strip-leading-paths",
66
65
  "build:types": "tsc --emitDeclarationOnly --outDir dist",
67
- "clean": "rimraf -g {dist,*.tsbuildinfo}",
68
- "lint": "eslint .",
69
- "lint:fix": "eslint . --fix"
66
+ "clean": "rimraf -g {dist,*.tsbuildinfo}"
70
67
  }
71
68
  }