@payloadcms/db-mongodb 3.71.0-internal.ef75fa0 → 3.71.0
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.
- package/dist/find.d.ts.map +1 -1
- package/dist/find.js +1 -0
- package/dist/find.js.map +1 -1
- package/dist/findGlobalVersions.d.ts.map +1 -1
- package/dist/findGlobalVersions.js +3 -1
- package/dist/findGlobalVersions.js.map +1 -1
- package/dist/findVersions.d.ts.map +1 -1
- package/dist/findVersions.js +3 -1
- package/dist/findVersions.js.map +1 -1
- package/dist/index.d.ts +10 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/queries/sanitizeQueryValue.d.ts.map +1 -1
- package/dist/queries/sanitizeQueryValue.js +13 -3
- package/dist/queries/sanitizeQueryValue.js.map +1 -1
- package/dist/utilities/buildJoinAggregation.d.ts.map +1 -1
- package/dist/utilities/buildJoinAggregation.js +2 -1
- package/dist/utilities/buildJoinAggregation.js.map +1 -1
- package/dist/utilities/compatibilityOptions.d.ts +2 -0
- package/dist/utilities/compatibilityOptions.d.ts.map +1 -1
- package/dist/utilities/compatibilityOptions.js +2 -0
- package/dist/utilities/compatibilityOptions.js.map +1 -1
- package/package.json +3 -3
package/dist/find.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../src/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AAgBnC,eAAO,MAAM,IAAI,EAAE,
|
|
1
|
+
{"version":3,"file":"find.d.ts","sourceRoot":"","sources":["../src/find.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAA;AAgBnC,eAAO,MAAM,IAAI,EAAE,IAgKlB,CAAA"}
|
package/dist/find.js
CHANGED
package/dist/find.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/find.ts"],"sourcesContent":["import type { PaginateOptions, PipelineStage } from 'mongoose'\nimport type { Find } from 'payload'\n\nimport { flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { aggregatePaginate } from './utilities/aggregatePaginate.js'\nimport { buildJoinAggregation } from './utilities/buildJoinAggregation.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { resolveJoins } from './utilities/resolveJoins.js'\nimport { transform } from './utilities/transform.js'\n\nexport const find: Find = async function find(\n this: MongooseAdapter,\n {\n collection: collectionSlug,\n draftsEnabled,\n joins = {},\n limit = 0,\n locale,\n page,\n pagination,\n projection,\n req,\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const sortAggregation: PipelineStage[] = []\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n sortAggregation,\n timestamps: collectionConfig.timestamps || false,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n options: {\n session,\n },\n page,\n pagination,\n projection,\n sort,\n useEstimatedCount,\n }\n\n if (select) {\n paginationOptions.projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n })\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n hint: { _id: 1 },\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n let result\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n query,\n })\n\n if (aggregate || sortAggregation.length > 0) {\n result = await aggregatePaginate({\n adapter: this,\n collation: paginationOptions.collation,\n joinAggregation: aggregate,\n limit: paginationOptions.limit,\n Model,\n page: paginationOptions.page,\n pagination: paginationOptions.pagination,\n projection: paginationOptions.projection,\n query,\n session: paginationOptions.options?.session ?? undefined,\n sort: paginationOptions.sort as object,\n sortAggregation,\n useEstimatedCount: paginationOptions.useEstimatedCount,\n })\n } else {\n result = await Model.paginate(query, paginationOptions)\n }\n\n if (!this.useJoinAggregations) {\n await resolveJoins({\n adapter: this,\n collectionSlug,\n docs: result.docs as Record<string, unknown>[],\n joins,\n locale,\n })\n }\n\n transform({\n adapter: this,\n data: result.docs,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return result\n}\n"],"names":["flattenWhereToOperators","buildQuery","buildSortParam","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","resolveJoins","transform","find","collection","collectionSlug","draftsEnabled","joins","limit","locale","page","pagination","projection","req","select","sort","sortArg","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","session","useEstimatedCount","length","paginationOptions","lean","leanWithId","options","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","joinAggregation","undefined","paginate","useJoinAggregations","docs","data","operation"],"mappings":"AAGA,SAASA,uBAAuB,QAAQ,UAAS;AAIjD,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,YAAY,QAAQ,8BAA6B;AAC1D,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,OAAa,eAAeA,KAEvC,EACEC,YAAYC,cAAc,EAC1BC,aAAa,EACbC,QAAQ,CAAC,CAAC,EACVC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,MAAMC,OAAO,EACbC,QAAQ,CAAC,CAAC,EACX;IAED,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGpB,cAAc;QAAEqB,SAAS,IAAI;QAAEf;IAAe;IAElF,IAAIgB,oBAAoB;IAExB,IAAIJ,OAAO;QACT,MAAMK,cAAc7B,wBAAwBwB;QAC5CI,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IA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Be,MAAM;oBAAEC,KAAK;gBAAE;gBACff;YACF;QAEJ;IACF;IAEA,IAAI5B,SAAS,GAAG;QACd+B,kBAAkB/B,KAAK,GAAGA;QAC1B,qEAAqE;QAErE+B,kBAAkBG,OAAO,CAAElC,KAAK,GAAGA;QAEnC,mCAAmC;QACnC,IAAIA,UAAU,GAAG;YACf+B,kBAAkB5B,UAAU,GAAG;QACjC;IACF;IAEA,IAAIyC;IAEJ,MAAMC,YAAY,MAAMxD,qBAAqB;QAC3CuB,SAAS,IAAI;QACbhB,YAAYC;QACZa;QACAZ;QACAC;QACAE;
|
|
1
|
+
{"version":3,"sources":["../src/find.ts"],"sourcesContent":["import type { PaginateOptions, PipelineStage } from 'mongoose'\nimport type { Find } from 'payload'\n\nimport { flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { aggregatePaginate } from './utilities/aggregatePaginate.js'\nimport { buildJoinAggregation } from './utilities/buildJoinAggregation.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { resolveJoins } from './utilities/resolveJoins.js'\nimport { transform } from './utilities/transform.js'\n\nexport const find: Find = async function find(\n this: MongooseAdapter,\n {\n collection: collectionSlug,\n draftsEnabled,\n joins = {},\n limit = 0,\n locale,\n page,\n pagination,\n projection,\n req,\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n const sortAggregation: PipelineStage[] = []\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale,\n sort: sortArg || collectionConfig.defaultSort,\n sortAggregation,\n timestamps: collectionConfig.timestamps || false,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n options: {\n session,\n },\n page,\n pagination,\n projection,\n sort,\n useEstimatedCount,\n }\n\n if (select) {\n paginationOptions.projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n })\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n hint: { _id: 1 },\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n let result\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection: paginationOptions.projection,\n query,\n })\n\n if (aggregate || sortAggregation.length > 0) {\n result = await aggregatePaginate({\n adapter: this,\n collation: paginationOptions.collation,\n joinAggregation: aggregate,\n limit: paginationOptions.limit,\n Model,\n page: paginationOptions.page,\n pagination: paginationOptions.pagination,\n projection: paginationOptions.projection,\n query,\n session: paginationOptions.options?.session ?? undefined,\n sort: paginationOptions.sort as object,\n sortAggregation,\n useEstimatedCount: paginationOptions.useEstimatedCount,\n })\n } else {\n result = await Model.paginate(query, paginationOptions)\n }\n\n if (!this.useJoinAggregations) {\n await resolveJoins({\n adapter: this,\n collectionSlug,\n docs: result.docs as Record<string, unknown>[],\n joins,\n locale,\n })\n }\n\n transform({\n adapter: this,\n data: result.docs,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return result\n}\n"],"names":["flattenWhereToOperators","buildQuery","buildSortParam","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","resolveJoins","transform","find","collection","collectionSlug","draftsEnabled","joins","limit","locale","page","pagination","projection","req","select","sort","sortArg","where","collectionConfig","Model","adapter","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","session","useEstimatedCount","length","paginationOptions","lean","leanWithId","options","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","joinAggregation","undefined","paginate","useJoinAggregations","docs","data","operation"],"mappings":"AAGA,SAASA,uBAAuB,QAAQ,UAAS;AAIjD,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,iBAAiB,QAAQ,mCAAkC;AACpE,SAASC,oBAAoB,QAAQ,sCAAqC;AAC1E,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,YAAY,QAAQ,8BAA6B;AAC1D,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,OAAa,eAAeA,KAEvC,EACEC,YAAYC,cAAc,EAC1BC,aAAa,EACbC,QAAQ,CAAC,CAAC,EACVC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,E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ACLe,SAAS,MAAMjC,MAAMqC,QAAQ,CAACrB,OAAOI;IACvC;IAEA,IAAI,CAAC,IAAI,CAACkB,mBAAmB,EAAE;QAC7B,MAAMxD,aAAa;YACjBmB,SAAS,IAAI;YACbf;YACAqD,MAAMN,OAAOM,IAAI;YACjBnD;YACAE;QACF;IACF;IAEAP,UAAU;QACRkB,SAAS,IAAI;QACbuC,MAAMP,OAAOM,IAAI;QACjB3B,QAAQb,iBAAiBa,MAAM;QAC/B6B,WAAW;IACb;IAEA,OAAOR;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findGlobalVersions.d.ts","sourceRoot":"","sources":["../src/findGlobalVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAajD,eAAO,MAAM,kBAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"findGlobalVersions.d.ts","sourceRoot":"","sources":["../src/findGlobalVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AAajD,eAAO,MAAM,kBAAkB,EAAE,kBAgHhC,CAAA"}
|
|
@@ -5,7 +5,7 @@ import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect
|
|
|
5
5
|
import { getGlobal } from './utilities/getEntity.js';
|
|
6
6
|
import { getSession } from './utilities/getSession.js';
|
|
7
7
|
import { transform } from './utilities/transform.js';
|
|
8
|
-
export const findGlobalVersions = async function findGlobalVersions({ global: globalSlug, limit = 0, locale, page, pagination, req, select,
|
|
8
|
+
export const findGlobalVersions = async function findGlobalVersions({ global: globalSlug, limit = 0, locale, page, pagination, req, select, sort: sortArg, where = {} }) {
|
|
9
9
|
const { globalConfig, Model } = getGlobal({
|
|
10
10
|
adapter: this,
|
|
11
11
|
globalSlug,
|
|
@@ -35,6 +35,8 @@ export const findGlobalVersions = async function findGlobalVersions({ global: gl
|
|
|
35
35
|
where
|
|
36
36
|
});
|
|
37
37
|
const session = await getSession(this, req);
|
|
38
|
+
// Calculate skip from page for cases where pagination is disabled but offset is still needed
|
|
39
|
+
const skip = typeof page === 'number' && page > 1 ? (page - 1) * (limit || 0) : undefined;
|
|
38
40
|
const options = {
|
|
39
41
|
limit,
|
|
40
42
|
session,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/findGlobalVersions.ts"],"sourcesContent":["import type { PaginateOptions, QueryOptions } from 'mongoose'\nimport type { FindGlobalVersions } from 'payload'\n\nimport { APIError, buildVersionGlobalFields, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions(\n this: MongooseAdapter,\n {\n global: globalSlug,\n limit = 0,\n locale,\n page,\n pagination,\n req,\n select,\n
|
|
1
|
+
{"version":3,"sources":["../src/findGlobalVersions.ts"],"sourcesContent":["import type { PaginateOptions, QueryOptions } from 'mongoose'\nimport type { FindGlobalVersions } from 'payload'\n\nimport { APIError, buildVersionGlobalFields, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions(\n this: MongooseAdapter,\n {\n global: globalSlug,\n limit = 0,\n locale,\n page,\n pagination,\n req,\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { globalConfig, Model } = getGlobal({ adapter: this, globalSlug, versions: true })\n\n const versionFields = buildVersionGlobalFields(this.payload.config, globalConfig, true)\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: versionFields,\n locale,\n sort: sortArg || '-updatedAt',\n timestamps: true,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n fields: versionFields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n // Calculate skip from page for cases where pagination is disabled but offset is still needed\n const skip = typeof page === 'number' && page > 1 ? (page - 1) * (limit || 0) : undefined\n const options: QueryOptions = {\n limit,\n session,\n skip,\n }\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n limit,\n options,\n page,\n pagination,\n projection: buildProjectionFromSelect({ adapter: this, fields: versionFields, select }),\n sort,\n useEstimatedCount,\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n hint: { _id: 1 },\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n const result = await Model.paginate(query, paginationOptions)\n\n transform({\n adapter: this,\n data: result.docs,\n fields: buildVersionGlobalFields(this.payload.config, globalConfig),\n operation: 'read',\n })\n\n return result\n}\n"],"names":["buildVersionGlobalFields","flattenWhereToOperators","buildQuery","buildSortParam","buildProjectionFromSelect","getGlobal","getSession","transform","findGlobalVersions","global","globalSlug","limit","locale","page","pagination","req","select","sort","sortArg","where","globalConfig","Model","adapter","versions","versionFields","payload","config","hasNearConstraint","constraints","some","prop","Object","keys","key","fields","timestamps","query","session","skip","undefined","options","useEstimatedCount","length","paginationOptions","lean","leanWithId","projection","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","paginate","data","docs","operation"],"mappings":"AAGA,SAAmBA,wBAAwB,EAAEC,uBAAuB,QAAQ,UAAS;AAIrF,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,qBAAyC,eAAeA,mBAEnE,EACEC,QAAQC,UAAU,EAClBC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,MAAMC,OAAO,EACbC,QAAQ,CAAC,CAAC,EACX;IAED,MAAM,EAAEC,YAAY,EAAEC,KAAK,EAAE,GAAGhB,UAAU;QAAEiB,SAAS,IAAI;QAAEZ;QAAYa,UAAU;IAAK;IAEtF,MAAMC,gBAAgBxB,yBAAyB,IAAI,CAACyB,OAAO,CAACC,MAAM,EAAEN,cAAc;IAElF,IAAIO,oBAAoB;IAExB,IAAIR,OAAO;QACT,MAAMS,cAAc3B,wBAAwBkB;QAC5CQ,oBAAoBC,YAAYC,IAAI,CA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nC,OAAOC,QAAQC,OAAO,CACpB/B,MAAMgC,cAAc,CAACjB,OAAO;gBAC1BkB,MAAM;oBAAEC,KAAK;gBAAE;gBACflB;YACF;QAEJ;IACF;IAEA,IAAI1B,SAAS,GAAG;QACdgC,kBAAkBhC,KAAK,GAAGA;QAC1B,qEAAqE;QAErEgC,kBAAkBH,OAAO,CAAE7B,KAAK,GAAGA;QAEnC,mCAAmC;QACnC,IAAIA,UAAU,GAAG;YACfgC,kBAAkB7B,UAAU,GAAG;QACjC;IACF;IAEA,MAAM0C,SAAS,MAAMnC,MAAMoC,QAAQ,CAACrB,OAAOO;IAE3CpC,UAAU;QACRe,SAAS,IAAI;QACboC,MAAMF,OAAOG,IAAI;QACjBzB,QAAQlC,yBAAyB,IAAI,CAACyB,OAAO,CAACC,MAAM,EAAEN;QACtDwC,WAAW;IACb;IAEA,OAAOJ;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findVersions.d.ts","sourceRoot":"","sources":["../src/findVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAa3C,eAAO,MAAM,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"findVersions.d.ts","sourceRoot":"","sources":["../src/findVersions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAa3C,eAAO,MAAM,YAAY,EAAE,YAwH1B,CAAA"}
|
package/dist/findVersions.js
CHANGED
|
@@ -5,7 +5,7 @@ import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect
|
|
|
5
5
|
import { getCollection } from './utilities/getEntity.js';
|
|
6
6
|
import { getSession } from './utilities/getSession.js';
|
|
7
7
|
import { transform } from './utilities/transform.js';
|
|
8
|
-
export const findVersions = async function findVersions({ collection: collectionSlug, limit = 0, locale, page, pagination, req = {}, select,
|
|
8
|
+
export const findVersions = async function findVersions({ collection: collectionSlug, limit = 0, locale, page, pagination, req = {}, select, sort: sortArg, where = {} }) {
|
|
9
9
|
const { collectionConfig, Model } = getCollection({
|
|
10
10
|
adapter: this,
|
|
11
11
|
collectionSlug,
|
|
@@ -35,6 +35,8 @@ export const findVersions = async function findVersions({ collection: collection
|
|
|
35
35
|
where
|
|
36
36
|
});
|
|
37
37
|
const session = await getSession(this, req);
|
|
38
|
+
// Calculate skip from page for cases where pagination is disabled but offset is still needed
|
|
39
|
+
const skip = typeof page === 'number' && page > 1 ? (page - 1) * (limit || 0) : undefined;
|
|
38
40
|
const options = {
|
|
39
41
|
limit,
|
|
40
42
|
session,
|
package/dist/findVersions.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/findVersions.ts"],"sourcesContent":["import type { PaginateOptions, QueryOptions } from 'mongoose'\nimport type { FindVersions } from 'payload'\n\nimport { buildVersionCollectionFields, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const findVersions: FindVersions = async function findVersions(\n this: MongooseAdapter,\n {\n collection: collectionSlug,\n limit = 0,\n locale,\n page,\n pagination,\n req = {},\n select,\n
|
|
1
|
+
{"version":3,"sources":["../src/findVersions.ts"],"sourcesContent":["import type { PaginateOptions, QueryOptions } from 'mongoose'\nimport type { FindVersions } from 'payload'\n\nimport { buildVersionCollectionFields, flattenWhereToOperators } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const findVersions: FindVersions = async function findVersions(\n this: MongooseAdapter,\n {\n collection: collectionSlug,\n limit = 0,\n locale,\n page,\n pagination,\n req = {},\n select,\n sort: sortArg,\n where = {},\n },\n) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug,\n versions: true,\n })\n\n let hasNearConstraint = false\n\n if (where) {\n const constraints = flattenWhereToOperators(where)\n hasNearConstraint = constraints.some((prop) => Object.keys(prop).some((key) => key === 'near'))\n }\n\n let sort\n if (!hasNearConstraint) {\n sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale,\n sort: sortArg || '-updatedAt',\n timestamps: true,\n })\n }\n\n const fields = buildVersionCollectionFields(this.payload.config, collectionConfig, true)\n\n const query = await buildQuery({\n adapter: this,\n fields,\n locale,\n where,\n })\n\n const session = await getSession(this, req)\n // Calculate skip from page for cases where pagination is disabled but offset is still needed\n const skip = typeof page === 'number' && page > 1 ? (page - 1) * (limit || 0) : undefined\n const options: QueryOptions = {\n limit,\n session,\n skip,\n }\n\n // useEstimatedCount is faster, but not accurate, as it ignores any filters. It is thus set to true if there are no filters.\n const useEstimatedCount = hasNearConstraint || !query || Object.keys(query).length === 0\n const paginationOptions: PaginateOptions = {\n lean: true,\n leanWithId: true,\n limit,\n options,\n page,\n pagination,\n projection: buildProjectionFromSelect({\n adapter: this,\n fields,\n select,\n }),\n sort,\n useEstimatedCount,\n }\n\n if (this.collation) {\n const defaultLocale = 'en'\n paginationOptions.collation = {\n locale: locale && locale !== 'all' && locale !== '*' ? locale : defaultLocale,\n ...this.collation,\n }\n }\n\n if (!useEstimatedCount && Object.keys(query).length === 0 && this.disableIndexHints !== true) {\n // Improve the performance of the countDocuments query which is used if useEstimatedCount is set to false by adding\n // a hint. By default, if no hint is provided, MongoDB does not use an indexed field to count the returned documents,\n // which makes queries very slow. This only happens when no query (filter) is provided. If one is provided, it uses\n // the correct indexed field\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n hint: { _id: 1 },\n session,\n }),\n )\n }\n }\n\n if (limit >= 0) {\n paginationOptions.limit = limit\n // limit must also be set here, it's ignored when pagination is false\n\n paginationOptions.options!.limit = limit\n\n // Disable pagination if limit is 0\n if (limit === 0) {\n paginationOptions.pagination = false\n }\n }\n\n const result = await Model.paginate(query, paginationOptions)\n\n transform({\n adapter: this,\n data: result.docs,\n fields: buildVersionCollectionFields(this.payload.config, collectionConfig),\n operation: 'read',\n })\n\n return result\n}\n"],"names":["buildVersionCollectionFields","flattenWhereToOperators","buildQuery","buildSortParam","buildProjectionFromSelect","getCollection","getSession","transform","findVersions","collection","collectionSlug","limit","locale","page","pagination","req","select","sort","sortArg","where","collectionConfig","Model","adapter","versions","hasNearConstraint","constraints","some","prop","Object","keys","key","config","payload","fields","flattenedFields","timestamps","query","session","skip","undefined","options","useEstimatedCount","length","paginationOptions","lean","leanWithId","projection","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","paginate","data","docs","operation"],"mappings":"AAGA,SAASA,4BAA4B,EAAEC,uBAAuB,QAAQ,UAAS;AAI/E,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,yBAAyB,QAAQ,2CAA0C;AACpF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,eAA6B,eAAeA,aAEvD,EACEC,YAAYC,cAAc,EAC1BC,QAAQ,CAAC,EACTC,MAAM,EACNC,IAAI,EACJC,UAAU,EACVC,MAAM,CAAC,CAAC,EACRC,MAAM,EACNC,MAAMC,OAAO,EACbC,QAAQ,CAAC,CAAC,EACX;IAED,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGhB,cAAc;QAChDiB,SAAS,IAAI;QACbZ;QACAa,UAA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I,CAACN,qBAAqBb,OAAOC,IAAI,CAACO,OAAOM,MAAM,KAAK,KAAK,IAAI,CAACO,iBAAiB,KAAK,MAAM;QAC5F,mHAAmH;QACnH,qHAAqH;QACrH,mHAAmH;QACnH,4BAA4B;QAC5BN,kBAAkBO,gBAAgB,GAAG;YACnC,OAAOC,QAAQC,OAAO,CACpB/B,MAAMgC,cAAc,CAACjB,OAAO;gBAC1BkB,MAAM;oBAAEC,KAAK;gBAAE;gBACflB;YACF;QAEJ;IACF;IAEA,IAAI1B,SAAS,GAAG;QACdgC,kBAAkBhC,KAAK,GAAGA;QAC1B,qEAAqE;QAErEgC,kBAAkBH,OAAO,CAAE7B,KAAK,GAAGA;QAEnC,mCAAmC;QACnC,IAAIA,UAAU,GAAG;YACfgC,kBAAkB7B,UAAU,GAAG;QACjC;IACF;IAEA,MAAM0C,SAAS,MAAMnC,MAAMoC,QAAQ,CAACrB,OAAOO;IAE3CpC,UAAU;QACRe,SAAS,IAAI;QACboC,MAAMF,OAAOG,IAAI;QACjB1B,QAAQjC,6BAA6B,IAAI,CAACgC,OAAO,CAACD,MAAM,EAAEX;QAC1DwC,WAAW;IACb;IAEA,OAAOJ;AACT,EAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -27,6 +27,14 @@ export interface Args {
|
|
|
27
27
|
allowIDOnCreate?: boolean;
|
|
28
28
|
/** Set to false to disable auto-pluralization of collection names, Defaults to true */
|
|
29
29
|
autoPluralization?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* When true, bulk operations will process documents one at a time
|
|
32
|
+
* in separate transactions instead of all at once in a single transaction.
|
|
33
|
+
* Useful for avoiding transaction limitations with large datasets in DocumentDB and Cosmos DB.
|
|
34
|
+
*
|
|
35
|
+
* @default false
|
|
36
|
+
*/
|
|
37
|
+
bulkOperationsSingleTransaction?: boolean;
|
|
30
38
|
/**
|
|
31
39
|
* If enabled, collation allows for language-specific rules for string comparison.
|
|
32
40
|
* This configuration can include the following options:
|
|
@@ -109,6 +117,7 @@ export interface Args {
|
|
|
109
117
|
export type MongooseAdapter = {
|
|
110
118
|
afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void;
|
|
111
119
|
afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void;
|
|
120
|
+
bulkOperationsSingleTransaction: boolean;
|
|
112
121
|
collections: {
|
|
113
122
|
[slug: string]: CollectionModel;
|
|
114
123
|
};
|
|
@@ -167,6 +176,6 @@ declare module 'payload' {
|
|
|
167
176
|
};
|
|
168
177
|
}
|
|
169
178
|
}
|
|
170
|
-
export declare function mongooseAdapter({ afterCreateConnection, afterOpenConnection, allowAdditionalKeys, allowIDOnCreate, autoPluralization, collation, collectionsSchemaOptions, connectOptions, disableFallbackSort, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, useAlternativeDropDatabase, useBigIntForNumberIDs, useJoinAggregations, usePipelineInSortLookup, }: Args): DatabaseAdapterObj;
|
|
179
|
+
export declare function mongooseAdapter({ afterCreateConnection, afterOpenConnection, allowAdditionalKeys, allowIDOnCreate, autoPluralization, bulkOperationsSingleTransaction, collation, collectionsSchemaOptions, connectOptions, disableFallbackSort, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, useAlternativeDropDatabase, useBigIntForNumberIDs, useJoinAggregations, usePipelineInSortLookup, }: Args): DatabaseAdapterObj;
|
|
171
180
|
export { compatibilityOptions } from './utilities/compatibilityOptions.js';
|
|
172
181
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAA;AACnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAC/D,OAAO,K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O,CAAC,EAAE,YAAY,CAAA;SAAE,GAAG,aAAa,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAA;QAClF,aAAa,EAAE,CAAC,CAAC,SAAS,UAAU,GAAG,UAAU,EAC/C,IAAI,EAAE;YAAE,OAAO,CAAC,EAAE,YAAY,CAAA;SAAE,GAAG,iBAAiB,CAAC,CAAC,CAAC,KACpD,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAA;QAChC,0BAA0B,EAAE,OAAO,CAAA;QACnC,qBAAqB,EAAE,OAAO,CAAA;QAC9B,mBAAmB,EAAE,OAAO,CAAA;QAC5B,uBAAuB,EAAE,OAAO,CAAA;QAChC,QAAQ,EAAE;YACR,CAAC,IAAI,EAAE,MAAM,GAAG,eAAe,CAAA;SAChC,CAAA;KACF;CACF;AAED,wBAAgB,eAAe,CAAC,EAC9B,qBAAqB,EACrB,mBAAmB,EACnB,mBAA2B,EAC3B,eAAuB,EACvB,iBAAwB,EACxB,+BAAuC,EACvC,SAAS,EACT,wBAA6B,EAC7B,cAAc,EACd,mBAA2B,EAC3B,iBAAyB,EACzB,aAAqB,EACrB,YAAY,EAAE,eAAe,EAC7B,iBAAiB,EACjB,cAAc,EACd,kBAAuB,EACvB,GAAG,EACH,0BAAkC,EAClC,qBAA6B,EAC7B,mBAA0B,EAC1B,uBAA8B,GAC/B,EAAE,IAAI,GAAG,kBAAkB,CAmF3B;AAED,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -32,7 +32,7 @@ import { updateMany } from './updateMany.js';
|
|
|
32
32
|
import { updateOne } from './updateOne.js';
|
|
33
33
|
import { updateVersion } from './updateVersion.js';
|
|
34
34
|
import { upsert } from './upsert.js';
|
|
35
|
-
export function mongooseAdapter({ afterCreateConnection, afterOpenConnection, allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, collation, collectionsSchemaOptions = {}, connectOptions, disableFallbackSort = false, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url, useAlternativeDropDatabase = false, useBigIntForNumberIDs = false, useJoinAggregations = true, usePipelineInSortLookup = true }) {
|
|
35
|
+
export function mongooseAdapter({ afterCreateConnection, afterOpenConnection, allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, bulkOperationsSingleTransaction = false, collation, collectionsSchemaOptions = {}, connectOptions, disableFallbackSort = false, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url, useAlternativeDropDatabase = false, useBigIntForNumberIDs = false, useJoinAggregations = true, usePipelineInSortLookup = true }) {
|
|
36
36
|
function adapter({ payload }) {
|
|
37
37
|
const migrationDir = findMigrationDir(migrationDirArg);
|
|
38
38
|
mongoose.set('strictQuery', false);
|
|
@@ -42,6 +42,7 @@ export function mongooseAdapter({ afterCreateConnection, afterOpenConnection, al
|
|
|
42
42
|
afterCreateConnection,
|
|
43
43
|
afterOpenConnection,
|
|
44
44
|
autoPluralization,
|
|
45
|
+
bulkOperationsSingleTransaction,
|
|
45
46
|
collation,
|
|
46
47
|
collections: {},
|
|
47
48
|
// @ts-expect-error initialize without a connection
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n JsonObject,\n Payload,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport { createDatabaseAdapter, defaultBeginTransaction, findMigrationDir } from 'payload'\n\nimport type {\n CollectionModel,\n GlobalModel,\n MigrateDownArgs,\n MigrateUpArgs,\n MongooseMigration,\n} from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findDistinct } from './findDistinct.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /**\n * We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.\n * This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.\n *\n * Set to `true` to disable this behaviour.\n */\n disableFallbackSort?: boolean\n /** 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 */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: MongooseMigration[]\n\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n\n /**\n * Set to `true` to use an alternative `dropDatabase` implementation that calls `collection.deleteMany({})` on every collection instead of sending a raw `dropDatabase` command.\n * Payload only uses `dropDatabase` for testing purposes.\n * @default false\n */\n useAlternativeDropDatabase?: boolean\n\n /**\n * Set to `true` to use `BigInt` for custom ID fields of type `'number'`.\n * Useful for databases that don't support `double` or `int32` IDs.\n * @default false\n */\n useBigIntForNumberIDs?: boolean\n /**\n * Set to `false` to disable join aggregations (which use correlated subqueries) and instead populate join fields via multiple `find` queries.\n * @default true\n */\n useJoinAggregations?: boolean\n /**\n * Set to `false` to disable the use of `pipeline` in the `$lookup` aggregation in sorting.\n * @default true\n */\n usePipelineInSortLookup?: boolean\n}\n\nexport type MongooseAdapter = {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n afterCreateConnection,\n afterOpenConnection,\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n collation,\n collectionsSchemaOptions = {},\n connectOptions,\n disableFallbackSort = false,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n useAlternativeDropDatabase = false,\n useBigIntForNumberIDs = false,\n useJoinAggregations = true,\n usePipelineInSortLookup = true,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n afterCreateConnection,\n afterOpenConnection,\n autoPluralization,\n collation,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n disableFallbackSort,\n find,\n findDistinct,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFresh,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n useAlternativeDropDatabase,\n useBigIntForNumberIDs,\n useJoinAggregations,\n usePipelineInSortLookup,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\nexport { compatibilityOptions } from './utilities/compatibilityOptions.js'\n"],"names":["mongoose","createDatabaseAdapter","defaultBeginTransaction","findMigrationDir","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findDistinct","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","afterCreateConnection","afterOpenConnection","allowAdditionalKeys","allowIDOnCreate","autoPluralization","collation","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","useAlternativeDropDatabase","useBigIntForNumberIDs","useJoinAggregations","usePipelineInSortLookup","adapter","payload","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","compatibilityOptions"],"mappings":"AAsBA,OAAOA,cAAc,WAAU;AAC/B,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,gBAAgB,QAAQ,UAAS;AAU1F,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,KAAK,QAAQ,aAAY;AAClC,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,MAAM,QAAQ,cAAa;AACpC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,IAAI,QAAQ,YAAW;AAChC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,gBAAgB,QAAQ,qCAAoC;AACrE,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,SAAS,QAAQ,iBAAgB;AAC1C,SAASC,aAAa,QAAQ,qBAAo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;QACF;IACF;IAEA,OAAO;QACLI,MAAM;QACNrB;QACA4B,eAAe;QACf7C,MAAMmC;IACR;AACF;AAEA,SAASY,oBAAoB,QAAQ,sCAAqC"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { CollationOptions, TransactionOptions } from 'mongodb'\nimport type { MongoMemoryReplSet } from 'mongodb-memory-server'\nimport type {\n ClientSession,\n Connection,\n ConnectOptions,\n QueryOptions,\n SchemaOptions,\n} from 'mongoose'\nimport type {\n BaseDatabaseAdapter,\n CollectionSlug,\n DatabaseAdapterObj,\n JsonObject,\n Payload,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport mongoose from 'mongoose'\nimport { createDatabaseAdapter, defaultBeginTransaction, findMigrationDir } from 'payload'\n\nimport type {\n CollectionModel,\n GlobalModel,\n MigrateDownArgs,\n MigrateUpArgs,\n MongooseMigration,\n} from './types.js'\n\nimport { connect } from './connect.js'\nimport { count } from './count.js'\nimport { countGlobalVersions } from './countGlobalVersions.js'\nimport { countVersions } from './countVersions.js'\nimport { create } from './create.js'\nimport { createGlobal } from './createGlobal.js'\nimport { createGlobalVersion } from './createGlobalVersion.js'\nimport { createMigration } from './createMigration.js'\nimport { createVersion } from './createVersion.js'\nimport { deleteMany } from './deleteMany.js'\nimport { deleteOne } from './deleteOne.js'\nimport { deleteVersions } from './deleteVersions.js'\nimport { destroy } from './destroy.js'\nimport { find } from './find.js'\nimport { findDistinct } from './findDistinct.js'\nimport { findGlobal } from './findGlobal.js'\nimport { findGlobalVersions } from './findGlobalVersions.js'\nimport { findOne } from './findOne.js'\nimport { findVersions } from './findVersions.js'\nimport { init } from './init.js'\nimport { migrateFresh } from './migrateFresh.js'\nimport { queryDrafts } from './queryDrafts.js'\nimport { beginTransaction } from './transactions/beginTransaction.js'\nimport { commitTransaction } from './transactions/commitTransaction.js'\nimport { rollbackTransaction } from './transactions/rollbackTransaction.js'\nimport { updateGlobal } from './updateGlobal.js'\nimport { updateGlobalVersion } from './updateGlobalVersion.js'\nimport { updateJobs } from './updateJobs.js'\nimport { updateMany } from './updateMany.js'\nimport { updateOne } from './updateOne.js'\nimport { updateVersion } from './updateVersion.js'\nimport { upsert } from './upsert.js'\n\nexport type { MigrateDownArgs, MigrateUpArgs } from './types.js'\n\nexport interface Args {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n /**\n * By default, Payload strips all additional keys from MongoDB data that don't exist\n * in the Payload schema. If you have some data that you want to include to the result\n * but it doesn't exist in Payload, you can enable this flag\n * @default false\n */\n allowAdditionalKeys?: boolean\n /**\n * Enable this flag if you want to thread your own ID to create operation data, for example:\n * ```ts\n * import { Types } from 'mongoose'\n *\n * const id = new Types.ObjectId().toHexString()\n * const doc = await payload.create({ collection: 'posts', data: {id, title: \"my title\"}})\n * assertEq(doc.id, id)\n * ```\n */\n allowIDOnCreate?: boolean\n /** Set to false to disable auto-pluralization of collection names, Defaults to true */\n autoPluralization?: boolean\n /**\n * When true, bulk operations will process documents one at a time\n * in separate transactions instead of all at once in a single transaction.\n * Useful for avoiding transaction limitations with large datasets in DocumentDB and Cosmos DB.\n *\n * @default false\n */\n bulkOperationsSingleTransaction?: boolean\n\n /**\n * If enabled, collation allows for language-specific rules for string comparison.\n * This configuration can include the following options:\n *\n * - `strength` (number): Comparison level (1: Primary, 2: Secondary, 3: Tertiary (default), 4: Quaternary, 5: Identical)\n * - `caseLevel` (boolean): Include case comparison at strength level 1 or 2.\n * - `caseFirst` (string): Sort order of case differences during tertiary level comparisons (\"upper\", \"lower\", \"off\").\n * - `numericOrdering` (boolean): Compare numeric strings as numbers.\n * - `alternate` (string): Consider whitespace and punctuation as base characters (\"non-ignorable\", \"shifted\").\n * - `maxVariable` (string): Characters considered ignorable when `alternate` is \"shifted\" (\"punct\", \"space\").\n * - `backwards` (boolean): Sort strings with diacritics from back of the string.\n * - `normalization` (boolean): Check if text requires normalization and perform normalization.\n *\n * Available on MongoDB version 3.4 and up.\n * The locale that gets passed is your current project's locale but defaults to \"en\".\n *\n * Example:\n * {\n * strength: 3\n * }\n *\n * Defaults to disabled.\n */\n collation?: Omit<CollationOptions, 'locale'>\n\n collectionsSchemaOptions?: Partial<Record<CollectionSlug, SchemaOptions>>\n /** Extra configuration options */\n connectOptions?: {\n /**\n * Set false to disable $facet aggregation in non-supporting databases, Defaults to true\n * @deprecated Payload doesn't use `$facet` anymore anywhere.\n */\n useFacet?: boolean\n } & ConnectOptions\n /**\n * We add a secondary sort based on `createdAt` to ensure that results are always returned in the same order when sorting by a non-unique field.\n * This is because MongoDB does not guarantee the order of results, however in very large datasets this could affect performance.\n *\n * Set to `true` to disable this behaviour.\n */\n disableFallbackSort?: boolean\n /** 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 */\n disableIndexHints?: boolean\n /**\n * Set to `true` to ensure that indexes are ready before completing connection.\n * NOTE: not recommended for production. This can slow down the initialization of Payload.\n */\n ensureIndexes?: boolean\n migrationDir?: string\n /**\n * typed as any to avoid dependency\n */\n mongoMemoryServer?: MongoMemoryReplSet\n prodMigrations?: MongooseMigration[]\n\n transactionOptions?: false | TransactionOptions\n\n /** The URL to connect to MongoDB or false to start payload and prevent connecting */\n url: false | string\n\n /**\n * Set to `true` to use an alternative `dropDatabase` implementation that calls `collection.deleteMany({})` on every collection instead of sending a raw `dropDatabase` command.\n * Payload only uses `dropDatabase` for testing purposes.\n * @default false\n */\n useAlternativeDropDatabase?: boolean\n\n /**\n * Set to `true` to use `BigInt` for custom ID fields of type `'number'`.\n * Useful for databases that don't support `double` or `int32` IDs.\n * @default false\n */\n useBigIntForNumberIDs?: boolean\n /**\n * Set to `false` to disable join aggregations (which use correlated subqueries) and instead populate join fields via multiple `find` queries.\n * @default true\n */\n useJoinAggregations?: boolean\n /**\n * Set to `false` to disable the use of `pipeline` in the `$lookup` aggregation in sorting.\n * @default true\n */\n usePipelineInSortLookup?: boolean\n}\n\nexport type MongooseAdapter = {\n afterCreateConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n afterOpenConnection?: (adapter: MongooseAdapter) => Promise<void> | void\n bulkOperationsSingleTransaction: boolean\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n} & Args &\n BaseDatabaseAdapter\n\ndeclare module 'payload' {\n export interface DatabaseAdapter\n extends Omit<BaseDatabaseAdapter, 'sessions'>,\n Omit<Args, 'migrationDir'> {\n collections: {\n [slug: string]: CollectionModel\n }\n connection: Connection\n ensureIndexes: boolean\n globals: GlobalModel\n mongoMemoryServer: MongoMemoryReplSet\n prodMigrations?: {\n down: (args: MigrateDownArgs) => Promise<void>\n name: string\n up: (args: MigrateUpArgs) => Promise<void>\n }[]\n sessions: Record<number | string, ClientSession>\n transactionOptions: TransactionOptions\n updateGlobal: <T extends Record<string, unknown>>(\n args: { options?: QueryOptions } & UpdateGlobalArgs<T>,\n ) => Promise<T>\n updateGlobalVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends JsonObject = JsonObject>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n useAlternativeDropDatabase: boolean\n useBigIntForNumberIDs: boolean\n useJoinAggregations: boolean\n usePipelineInSortLookup: boolean\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n afterCreateConnection,\n afterOpenConnection,\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\n bulkOperationsSingleTransaction = false,\n collation,\n collectionsSchemaOptions = {},\n connectOptions,\n disableFallbackSort = false,\n disableIndexHints = false,\n ensureIndexes = false,\n migrationDir: migrationDirArg,\n mongoMemoryServer,\n prodMigrations,\n transactionOptions = {},\n url,\n useAlternativeDropDatabase = false,\n useBigIntForNumberIDs = false,\n useJoinAggregations = true,\n usePipelineInSortLookup = true,\n}: Args): DatabaseAdapterObj {\n function adapter({ payload }: { payload: Payload }) {\n const migrationDir = findMigrationDir(migrationDirArg)\n mongoose.set('strictQuery', false)\n\n return createDatabaseAdapter<MongooseAdapter>({\n name: 'mongoose',\n\n // Mongoose-specific\n afterCreateConnection,\n afterOpenConnection,\n autoPluralization,\n bulkOperationsSingleTransaction,\n collation,\n collections: {},\n // @ts-expect-error initialize without a connection\n connection: undefined,\n connectOptions: connectOptions || {},\n disableIndexHints,\n ensureIndexes,\n // @ts-expect-error don't have globals model yet\n globals: undefined,\n // @ts-expect-error Should not be required\n mongoMemoryServer,\n sessions: {},\n transactionOptions: transactionOptions === false ? undefined : transactionOptions,\n updateJobs,\n updateMany,\n url,\n versions: {},\n // DatabaseAdapter\n allowAdditionalKeys,\n allowIDOnCreate,\n beginTransaction: transactionOptions === false ? defaultBeginTransaction() : beginTransaction,\n collectionsSchemaOptions,\n commitTransaction,\n connect,\n count,\n countGlobalVersions,\n countVersions,\n create,\n createGlobal,\n createGlobalVersion,\n createMigration,\n createVersion,\n defaultIDType: 'text',\n deleteMany,\n deleteOne,\n deleteVersions,\n destroy,\n disableFallbackSort,\n find,\n findDistinct,\n findGlobal,\n findGlobalVersions,\n findOne,\n findVersions,\n init,\n migrateFresh,\n migrationDir,\n packageName: '@payloadcms/db-mongodb',\n payload,\n prodMigrations,\n queryDrafts,\n rollbackTransaction,\n updateGlobal,\n updateGlobalVersion,\n updateOne,\n updateVersion,\n upsert,\n useAlternativeDropDatabase,\n useBigIntForNumberIDs,\n useJoinAggregations,\n usePipelineInSortLookup,\n })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\nexport { compatibilityOptions } from './utilities/compatibilityOptions.js'\n"],"names":["mongoose","createDatabaseAdapter","defaultBeginTransaction","findMigrationDir","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findDistinct","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","afterCreateConnection","afterOpenConnection","allowAdditionalKeys","allowIDOnCreate","autoPluralization","bulkOperationsSingleTransaction","collation","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","useAlternativeDropDatabase","useBigIntForNumberIDs","useJoinAggregations","usePipelineInSortLookup","adapter","payload","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","compatibilityOptions"],"mappings":"AAsBA,OAAOA,cAAc,WAAU;AAC/B,SAASC,qBAAqB,EAAEC,uBAAuB,EAAEC,gBAAgB,QAAQ,UAAS;AAU1F,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,KAAK,QAAQ,aAAY;AAClC,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,aAAa,QAAQ,qBAAoB;AAClD,SAASC,MAAM,QAAQ,cAAa;AACpC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,mBAAmB,QAAQ,2BAA0B;AAC9D,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,aAAa,QA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0BAA0B,IAAI,EACzB;IACL,SAASC,QAAQ,EAAEC,OAAO,EAAwB;QAChD,MAAMX,eAAe9C,iBAAiB+C;QACtClD,SAAS6D,GAAG,CAAC,eAAe;QAE5B,OAAO5D,sBAAuC;YAC5C6D,MAAM;YAEN,oBAAoB;YACpBzB;YACAC;YACAG;YACAC;YACAC;YACAoB,aAAa,CAAC;YACd,mDAAmD;YACnDC,YAAYC;YACZpB,gBAAgBA,kBAAkB,CAAC;YACnCE;YACAC;YACA,gDAAgD;YAChDkB,SAASD;YACT,0CAA0C;YAC1Cd;YACAgB,UAAU,CAAC;YACXd,oBAAoBA,uBAAuB,QAAQY,YAAYZ;YAC/DtB;YACAC;YACAsB;YACAc,UAAU,CAAC;YACX,kBAAkB;YAClB7B;YACAC;YACAd,kBAAkB2B,uBAAuB,QAAQnD,4BAA4BwB;YAC7EkB;YACAjB;YACAvB;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAyD,eAAe;YACfxD;YACAC;YACAC;YACAC;YACA8B;YACA7B;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAyB;YACAqB,aAAa;YACbV;YACAR;YACA3B;YACAG;YACAC;YACAC;YACAG;YACAC;YACAC;YACAoB;YACAC;YACAC;YACAC;QACF;IACF;IAEA,OAAO;QACLI,MAAM;QACNtB;QACA6B,eAAe;QACf9C,MAAMoC;IACR;AACF;AAEA,SAASY,oBAAoB,QAAQ,sCAAqC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sanitizeQueryValue.d.ts","sourceRoot":"","sources":["../../src/queries/sanitizeQueryValue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,cAAc,EACd,QAAQ,EACR,OAAO,EAER,MAAM,SAAS,CAAA;AAMhB,KAAK,sBAAsB,GAAG;IAC5B,KAAK,EAAE,cAAc,CAAA;IACrB,WAAW,EAAE,OAAO,CAAA;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,QAAQ,CAAA;IAClB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,GAAG,CAAA;CACT,CAAA;AAoED,eAAO,MAAM,kBAAkB,qFAS5B,sBAAsB,KACrB;IACE,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;CACd,GACD,
|
|
1
|
+
{"version":3,"file":"sanitizeQueryValue.d.ts","sourceRoot":"","sources":["../../src/queries/sanitizeQueryValue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,cAAc,EACd,QAAQ,EACR,OAAO,EAER,MAAM,SAAS,CAAA;AAMhB,KAAK,sBAAsB,GAAG;IAC5B,KAAK,EAAE,cAAc,CAAA;IACrB,WAAW,EAAE,OAAO,CAAA;IACpB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,QAAQ,CAAA;IAClB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,GAAG,CAAA;CACT,CAAA;AAoED,eAAO,MAAM,kBAAkB,qFAS5B,sBAAsB,KACrB;IACE,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,GAAG,CAAC,EAAE,OAAO,CAAA;CACd,GACD,SAwWH,CAAA"}
|
|
@@ -383,12 +383,22 @@ export const sanitizeQueryValue = ({ field, hasCustomID, locale, operator, paren
|
|
|
383
383
|
}
|
|
384
384
|
if (operator === 'exists') {
|
|
385
385
|
formattedValue = formattedValue === 'true' || formattedValue === true;
|
|
386
|
-
|
|
387
|
-
|
|
386
|
+
let treatEmptyString = ![
|
|
387
|
+
'array',
|
|
388
|
+
'blocks',
|
|
388
389
|
'checkbox',
|
|
389
390
|
'relationship',
|
|
390
391
|
'upload'
|
|
391
|
-
].includes(field.type)
|
|
392
|
+
].includes(field.type);
|
|
393
|
+
if (field.type === 'text' && field.hasMany) {
|
|
394
|
+
treatEmptyString = false;
|
|
395
|
+
} else if (field.type === 'number' && field.hasMany) {
|
|
396
|
+
treatEmptyString = false;
|
|
397
|
+
} else if (field.type === 'select' && field.hasMany) {
|
|
398
|
+
treatEmptyString = false;
|
|
399
|
+
}
|
|
400
|
+
// _id can't be empty string, will error Cast to ObjectId failed for value ""
|
|
401
|
+
return buildExistsQuery(formattedValue, path, treatEmptyString);
|
|
392
402
|
}
|
|
393
403
|
}
|
|
394
404
|
if ((path === '_id' || path === 'parent') && operator === 'like' && formattedValue.length === 24 && !hasCustomID) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/queries/sanitizeQueryValue.ts"],"sourcesContent":["import type {\n FlattenedBlock,\n FlattenedBlocksField,\n FlattenedField,\n Operator,\n Payload,\n RelationshipField,\n} from 'payload'\n\nimport { Types } from 'mongoose'\nimport { createArrayFromCommaDelineated } from 'payload'\nimport { fieldShouldBeLocalized } from 'payload/shared'\n\ntype SanitizeQueryValueArgs = {\n field: FlattenedField\n hasCustomID: boolean\n locale?: string\n operator: Operator\n parentIsLocalized: boolean\n path: string\n payload: Payload\n val: any\n}\n\nconst buildExistsQuery = (formattedValue: unknown, path: string, treatEmptyString = true) => {\n if (formattedValue) {\n return {\n rawQuery: {\n $and: [\n { [path]: { $exists: true } },\n { [path]: { $ne: null } },\n ...(treatEmptyString ? [{ [path]: { $ne: '' } }] : []), // Treat empty string as null / undefined\n ],\n },\n }\n } else {\n return {\n rawQuery: {\n $or: [\n { [path]: { $exists: false } },\n { [path]: { $eq: null } },\n ...(treatEmptyString ? [{ [path]: { $eq: '' } }] : []), // Treat empty string as null / undefined\n ],\n },\n }\n }\n}\n\n// returns nestedField Field object from blocks.nestedField path because getLocalizedPaths splits them only for relationships\nconst getFieldFromSegments = ({\n field,\n payload,\n segments,\n}: {\n field: FlattenedBlock | FlattenedField\n payload: Payload\n segments: string[]\n}): FlattenedField | undefined => {\n if ('blocks' in field || 'blockReferences' in field) {\n const _field: FlattenedBlocksField = field as FlattenedBlocksField\n for (const _block of _field.blockReferences ?? _field.blocks) {\n const block: FlattenedBlock | undefined =\n typeof _block === 'string' ? payload.blocks[_block] : _block\n if (block) {\n const field = getFieldFromSegments({ field: block, payload, segments })\n if (field) {\n return field\n }\n }\n }\n }\n\n if ('fields' in field) {\n for (let i = 0; i < segments.length; i++) {\n const foundField = field.flattenedFields.find((each) => each.name === segments[i])\n\n if (!foundField) {\n break\n }\n\n if (foundField && segments.length - 1 === i) {\n return foundField\n }\n\n segments.shift()\n return getFieldFromSegments({ field: foundField, payload, segments })\n }\n }\n}\n\nexport const sanitizeQueryValue = ({\n field,\n hasCustomID,\n locale,\n operator,\n parentIsLocalized,\n path,\n payload,\n val,\n}: SanitizeQueryValueArgs):\n | {\n operator?: string\n rawQuery?: unknown\n val?: unknown\n }\n | undefined => {\n let formattedValue = val\n let formattedOperator = operator\n\n if (['array', 'blocks', 'group', 'tab'].includes(field.type) && path.includes('.')) {\n const segments = path.split('.')\n segments.shift()\n const foundField = getFieldFromSegments({ field, payload, segments })\n\n if (foundField) {\n field = foundField\n }\n }\n\n // Disregard invalid _ids\n if (path === '_id') {\n if (typeof val === 'string' && val.split(',').length === 1) {\n if (!hasCustomID) {\n const isValid = Types.ObjectId.isValid(val)\n\n if (!isValid) {\n return { operator: formattedOperator, val: undefined }\n } else {\n if (['in', 'not_in'].includes(operator)) {\n formattedValue = createArrayFromCommaDelineated(formattedValue).map(\n (id) => new Types.ObjectId(id),\n )\n } else {\n formattedValue = new Types.ObjectId(val)\n }\n }\n }\n\n if (field.type === 'number') {\n const parsedNumber = parseFloat(val)\n\n if (Number.isNaN(parsedNumber)) {\n return { operator: formattedOperator, val: undefined }\n }\n }\n } else if (Array.isArray(val) || (typeof val === 'string' && val.split(',').length > 1)) {\n if (typeof val === 'string') {\n formattedValue = createArrayFromCommaDelineated(val)\n }\n\n if (Array.isArray(formattedValue)) {\n formattedValue = formattedValue.reduce<unknown[]>((formattedValues, inVal) => {\n if (!hasCustomID) {\n if (Types.ObjectId.isValid(inVal)) {\n formattedValues.push(new Types.ObjectId(inVal))\n\n return formattedValues\n }\n }\n\n if (field.type === 'number') {\n const parsedNumber = parseFloat(inVal)\n if (!Number.isNaN(parsedNumber)) {\n formattedValues.push(parsedNumber)\n }\n } else {\n formattedValues.push(inVal)\n }\n\n return formattedValues\n }, [])\n }\n }\n }\n\n // Cast incoming values as proper searchable types\n if (field.type === 'checkbox' && typeof val === 'string') {\n if (val.toLowerCase() === 'true') {\n formattedValue = true\n }\n if (val.toLowerCase() === 'false') {\n formattedValue = false\n }\n }\n\n if (['all', 'in', 'not_in'].includes(operator) && typeof formattedValue === 'string') {\n formattedValue = createArrayFromCommaDelineated(formattedValue)\n\n if (field.type === 'number' && Array.isArray(formattedValue)) {\n formattedValue = formattedValue.map((arrayVal) => parseFloat(arrayVal))\n }\n }\n\n if (field.type === 'number') {\n if (typeof formattedValue === 'string' && operator !== 'exists') {\n formattedValue = Number(val)\n }\n\n if (operator === 'exists') {\n formattedValue = val === 'true' ? true : val === 'false' ? false : Boolean(val)\n\n return buildExistsQuery(formattedValue, path)\n }\n }\n\n if (field.type === 'date' && typeof val === 'string' && operator !== 'exists') {\n formattedValue = new Date(val)\n if (Number.isNaN(Date.parse(formattedValue))) {\n return undefined\n }\n }\n\n if (['relationship', 'upload'].includes(field.type)) {\n if (val === 'null') {\n formattedValue = null\n }\n\n // Object equality requires the value to be the first key in the object that is being queried.\n if (\n operator === 'equals' &&\n formattedValue &&\n typeof formattedValue === 'object' &&\n formattedValue.value &&\n formattedValue.relationTo\n ) {\n const { value } = formattedValue\n const isValid = Types.ObjectId.isValid(value)\n\n if (isValid) {\n formattedValue.value = new Types.ObjectId(value)\n }\n\n let localizedPath = path\n\n if (\n fieldShouldBeLocalized({ field, parentIsLocalized }) &&\n payload.config.localization &&\n locale\n ) {\n localizedPath = `${path}.${locale}`\n }\n\n return {\n rawQuery: {\n $or: [\n {\n [localizedPath]: {\n $eq: {\n // disable auto sort\n /* eslint-disable */\n value: formattedValue.value,\n relationTo: formattedValue.relationTo,\n /* eslint-enable */\n },\n },\n },\n {\n [localizedPath]: {\n $eq: {\n relationTo: formattedValue.relationTo,\n value: formattedValue.value,\n },\n },\n },\n ],\n },\n }\n }\n\n const relationTo = (field as RelationshipField).relationTo\n\n if (['in', 'not_in'].includes(operator) && Array.isArray(formattedValue)) {\n formattedValue = formattedValue.reduce((formattedValues, inVal) => {\n if (!inVal) {\n return formattedValues\n }\n\n if (typeof relationTo === 'string' && payload.collections[relationTo]?.customIDType) {\n if (payload.collections[relationTo].customIDType === 'number') {\n const parsedNumber = parseFloat(inVal)\n if (!Number.isNaN(parsedNumber)) {\n formattedValues.push(parsedNumber)\n return formattedValues\n }\n }\n\n formattedValues.push(inVal)\n return formattedValues\n }\n\n if (\n Array.isArray(relationTo) &&\n relationTo.some((relationTo) => !!payload.collections[relationTo]?.customIDType)\n ) {\n if (Types.ObjectId.isValid(inVal.toString())) {\n formattedValues.push(new Types.ObjectId(inVal))\n } else {\n formattedValues.push(inVal)\n }\n return formattedValues\n }\n\n if (Types.ObjectId.isValid(inVal.toString())) {\n formattedValues.push(new Types.ObjectId(inVal))\n }\n\n return formattedValues\n }, [])\n }\n\n if (\n ['contains', 'equals', 'like', 'not_equals'].includes(operator) &&\n (!Array.isArray(relationTo) || !path.endsWith('.relationTo'))\n ) {\n if (typeof relationTo === 'string') {\n const customIDType = payload.collections[relationTo]?.customIDType\n\n if (customIDType) {\n if (customIDType === 'number') {\n formattedValue = parseFloat(val)\n\n if (Number.isNaN(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n }\n } else {\n if (!Types.ObjectId.isValid(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n formattedValue = new Types.ObjectId(formattedValue)\n }\n } else {\n const hasCustomIDType = relationTo.some(\n (relationTo) => !!payload.collections[relationTo]?.customIDType,\n )\n\n if (hasCustomIDType) {\n if (typeof val === 'string') {\n const formattedNumber = Number(val)\n formattedValue = [Types.ObjectId.isValid(val) ? new Types.ObjectId(val) : val]\n formattedOperator = operator === 'not_equals' ? 'not_in' : 'in'\n if (!Number.isNaN(formattedNumber)) {\n formattedValue.push(formattedNumber)\n }\n }\n } else {\n if (!Types.ObjectId.isValid(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n formattedValue = new Types.ObjectId(formattedValue)\n }\n }\n }\n\n if (\n operator === 'all' &&\n Array.isArray(relationTo) &&\n path.endsWith('.value') &&\n Array.isArray(formattedValue)\n ) {\n formattedValue.forEach((v, i) => {\n if (Types.ObjectId.isValid(v)) {\n formattedValue[i] = new Types.ObjectId(v)\n }\n })\n }\n }\n\n // Set up specific formatting necessary by operators\n\n if (operator === 'near') {\n let lng\n let lat\n let maxDistance\n let minDistance\n\n if (Array.isArray(formattedValue)) {\n ;[lng, lat, maxDistance, minDistance] = formattedValue\n }\n\n if (typeof formattedValue === 'string') {\n ;[lng, lat, maxDistance, minDistance] = createArrayFromCommaDelineated(formattedValue)\n }\n\n if (lng == null || lat == null || (maxDistance == null && minDistance == null)) {\n formattedValue = undefined\n } else {\n formattedValue = {\n $geometry: { type: 'Point', coordinates: [parseFloat(lng), parseFloat(lat)] },\n }\n\n if (maxDistance && !Number.isNaN(Number(maxDistance))) {\n formattedValue.$maxDistance = parseFloat(maxDistance)\n }\n\n if (minDistance && !Number.isNaN(Number(minDistance))) {\n formattedValue.$minDistance = parseFloat(minDistance)\n }\n }\n }\n\n if (operator === 'within' || operator === 'intersects') {\n formattedValue = {\n $geometry: formattedValue,\n }\n }\n\n if (path !== '_id' || (path === '_id' && hasCustomID && field.type === 'text')) {\n if (operator === 'contains' && !Types.ObjectId.isValid(formattedValue)) {\n formattedValue = {\n $options: 'i',\n $regex: formattedValue.replace(/[\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'),\n }\n }\n\n if (operator === 'exists') {\n formattedValue = formattedValue === 'true' || formattedValue === true\n\n // _id can't be empty string, will error Cast to ObjectId failed for value \"\"\n return buildExistsQuery(\n formattedValue,\n path,\n !['checkbox', 'relationship', 'upload'].includes(field.type),\n )\n }\n }\n\n if (\n (path === '_id' || path === 'parent') &&\n operator === 'like' &&\n formattedValue.length === 24 &&\n !hasCustomID\n ) {\n formattedOperator = 'equals'\n }\n\n if (operator === 'exists') {\n formattedValue = formattedValue === 'true' || formattedValue === true\n\n // Clearable fields\n if (['relationship', 'select', 'upload'].includes(field.type)) {\n if (formattedValue) {\n return {\n rawQuery: {\n $and: [{ [path]: { $exists: true } }, { [path]: { $ne: null } }],\n },\n }\n } else {\n return {\n rawQuery: {\n $or: [{ [path]: { $exists: false } }, { [path]: { $eq: null } }],\n },\n }\n }\n }\n }\n\n return { operator: formattedOperator, val: formattedValue }\n}\n"],"names":["Types","createArrayFromCommaDelineated","fieldShouldBeLocalized","buildExistsQuery","formattedValue","path","treatEmptyString","rawQuery","$and","$exists","$ne","$or","$eq","getFieldFromSegments","field","payload","segments","_field","_block","blockReferences","blocks","block","i","length","foundField","flattenedFields","find","each","name","shift","sanitizeQueryValue","hasCustomID","locale","operator","parentIsLocalized","val","formattedOperator","includes","type","split","isValid","ObjectId","undefined","map","id","parsedNumber","parseFloat","Number","isNaN","Array","isArray","reduce","formattedValues","inVal","push","toLowerCase","arrayVal","Boolean","Date","parse","value","relationTo","localizedPath","config","localization","collections","customIDType","some","toString","endsWith","hasCustomIDType","formattedNumber","forEach","v","lng","lat","maxDistance","minDistance","$geometry","coordinates","$maxDistance","$minDistance","$options","$regex","replace"],"mappings":"AASA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,8BAA8B,QAAQ,UAAS;AACxD,SAASC,sBAAsB,QAAQ,iBAAgB;AAavD,MAAMC,mBAAmB,CAACC,gBAAyBC,MAAcC,mBAAmB,IAAI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/sanitizeQueryValue.ts"],"sourcesContent":["import type {\n FlattenedBlock,\n FlattenedBlocksField,\n FlattenedField,\n Operator,\n Payload,\n RelationshipField,\n} from 'payload'\n\nimport { Types } from 'mongoose'\nimport { createArrayFromCommaDelineated } from 'payload'\nimport { fieldShouldBeLocalized } from 'payload/shared'\n\ntype SanitizeQueryValueArgs = {\n field: FlattenedField\n hasCustomID: boolean\n locale?: string\n operator: Operator\n parentIsLocalized: boolean\n path: string\n payload: Payload\n val: any\n}\n\nconst buildExistsQuery = (formattedValue: unknown, path: string, treatEmptyString = true) => {\n if (formattedValue) {\n return {\n rawQuery: {\n $and: [\n { [path]: { $exists: true } },\n { [path]: { $ne: null } },\n ...(treatEmptyString ? [{ [path]: { $ne: '' } }] : []), // Treat empty string as null / undefined\n ],\n },\n }\n } else {\n return {\n rawQuery: {\n $or: [\n { [path]: { $exists: false } },\n { [path]: { $eq: null } },\n ...(treatEmptyString ? [{ [path]: { $eq: '' } }] : []), // Treat empty string as null / undefined\n ],\n },\n }\n }\n}\n\n// returns nestedField Field object from blocks.nestedField path because getLocalizedPaths splits them only for relationships\nconst getFieldFromSegments = ({\n field,\n payload,\n segments,\n}: {\n field: FlattenedBlock | FlattenedField\n payload: Payload\n segments: string[]\n}): FlattenedField | undefined => {\n if ('blocks' in field || 'blockReferences' in field) {\n const _field: FlattenedBlocksField = field as FlattenedBlocksField\n for (const _block of _field.blockReferences ?? _field.blocks) {\n const block: FlattenedBlock | undefined =\n typeof _block === 'string' ? payload.blocks[_block] : _block\n if (block) {\n const field = getFieldFromSegments({ field: block, payload, segments })\n if (field) {\n return field\n }\n }\n }\n }\n\n if ('fields' in field) {\n for (let i = 0; i < segments.length; i++) {\n const foundField = field.flattenedFields.find((each) => each.name === segments[i])\n\n if (!foundField) {\n break\n }\n\n if (foundField && segments.length - 1 === i) {\n return foundField\n }\n\n segments.shift()\n return getFieldFromSegments({ field: foundField, payload, segments })\n }\n }\n}\n\nexport const sanitizeQueryValue = ({\n field,\n hasCustomID,\n locale,\n operator,\n parentIsLocalized,\n path,\n payload,\n val,\n}: SanitizeQueryValueArgs):\n | {\n operator?: string\n rawQuery?: unknown\n val?: unknown\n }\n | undefined => {\n let formattedValue = val\n let formattedOperator = operator\n\n if (['array', 'blocks', 'group', 'tab'].includes(field.type) && path.includes('.')) {\n const segments = path.split('.')\n segments.shift()\n const foundField = getFieldFromSegments({ field, payload, segments })\n\n if (foundField) {\n field = foundField\n }\n }\n\n // Disregard invalid _ids\n if (path === '_id') {\n if (typeof val === 'string' && val.split(',').length === 1) {\n if (!hasCustomID) {\n const isValid = Types.ObjectId.isValid(val)\n\n if (!isValid) {\n return { operator: formattedOperator, val: undefined }\n } else {\n if (['in', 'not_in'].includes(operator)) {\n formattedValue = createArrayFromCommaDelineated(formattedValue).map(\n (id) => new Types.ObjectId(id),\n )\n } else {\n formattedValue = new Types.ObjectId(val)\n }\n }\n }\n\n if (field.type === 'number') {\n const parsedNumber = parseFloat(val)\n\n if (Number.isNaN(parsedNumber)) {\n return { operator: formattedOperator, val: undefined }\n }\n }\n } else if (Array.isArray(val) || (typeof val === 'string' && val.split(',').length > 1)) {\n if (typeof val === 'string') {\n formattedValue = createArrayFromCommaDelineated(val)\n }\n\n if (Array.isArray(formattedValue)) {\n formattedValue = formattedValue.reduce<unknown[]>((formattedValues, inVal) => {\n if (!hasCustomID) {\n if (Types.ObjectId.isValid(inVal)) {\n formattedValues.push(new Types.ObjectId(inVal))\n\n return formattedValues\n }\n }\n\n if (field.type === 'number') {\n const parsedNumber = parseFloat(inVal)\n if (!Number.isNaN(parsedNumber)) {\n formattedValues.push(parsedNumber)\n }\n } else {\n formattedValues.push(inVal)\n }\n\n return formattedValues\n }, [])\n }\n }\n }\n\n // Cast incoming values as proper searchable types\n if (field.type === 'checkbox' && typeof val === 'string') {\n if (val.toLowerCase() === 'true') {\n formattedValue = true\n }\n if (val.toLowerCase() === 'false') {\n formattedValue = false\n }\n }\n\n if (['all', 'in', 'not_in'].includes(operator) && typeof formattedValue === 'string') {\n formattedValue = createArrayFromCommaDelineated(formattedValue)\n\n if (field.type === 'number' && Array.isArray(formattedValue)) {\n formattedValue = formattedValue.map((arrayVal) => parseFloat(arrayVal))\n }\n }\n\n if (field.type === 'number') {\n if (typeof formattedValue === 'string' && operator !== 'exists') {\n formattedValue = Number(val)\n }\n\n if (operator === 'exists') {\n formattedValue = val === 'true' ? true : val === 'false' ? false : Boolean(val)\n return buildExistsQuery(formattedValue, path)\n }\n }\n\n if (field.type === 'date' && typeof val === 'string' && operator !== 'exists') {\n formattedValue = new Date(val)\n if (Number.isNaN(Date.parse(formattedValue))) {\n return undefined\n }\n }\n\n if (['relationship', 'upload'].includes(field.type)) {\n if (val === 'null') {\n formattedValue = null\n }\n\n // Object equality requires the value to be the first key in the object that is being queried.\n if (\n operator === 'equals' &&\n formattedValue &&\n typeof formattedValue === 'object' &&\n formattedValue.value &&\n formattedValue.relationTo\n ) {\n const { value } = formattedValue\n const isValid = Types.ObjectId.isValid(value)\n\n if (isValid) {\n formattedValue.value = new Types.ObjectId(value)\n }\n\n let localizedPath = path\n\n if (\n fieldShouldBeLocalized({ field, parentIsLocalized }) &&\n payload.config.localization &&\n locale\n ) {\n localizedPath = `${path}.${locale}`\n }\n\n return {\n rawQuery: {\n $or: [\n {\n [localizedPath]: {\n $eq: {\n // disable auto sort\n /* eslint-disable */\n value: formattedValue.value,\n relationTo: formattedValue.relationTo,\n /* eslint-enable */\n },\n },\n },\n {\n [localizedPath]: {\n $eq: {\n relationTo: formattedValue.relationTo,\n value: formattedValue.value,\n },\n },\n },\n ],\n },\n }\n }\n\n const relationTo = (field as RelationshipField).relationTo\n\n if (['in', 'not_in'].includes(operator) && Array.isArray(formattedValue)) {\n formattedValue = formattedValue.reduce((formattedValues, inVal) => {\n if (!inVal) {\n return formattedValues\n }\n\n if (typeof relationTo === 'string' && payload.collections[relationTo]?.customIDType) {\n if (payload.collections[relationTo].customIDType === 'number') {\n const parsedNumber = parseFloat(inVal)\n if (!Number.isNaN(parsedNumber)) {\n formattedValues.push(parsedNumber)\n return formattedValues\n }\n }\n\n formattedValues.push(inVal)\n return formattedValues\n }\n\n if (\n Array.isArray(relationTo) &&\n relationTo.some((relationTo) => !!payload.collections[relationTo]?.customIDType)\n ) {\n if (Types.ObjectId.isValid(inVal.toString())) {\n formattedValues.push(new Types.ObjectId(inVal))\n } else {\n formattedValues.push(inVal)\n }\n return formattedValues\n }\n\n if (Types.ObjectId.isValid(inVal.toString())) {\n formattedValues.push(new Types.ObjectId(inVal))\n }\n\n return formattedValues\n }, [])\n }\n\n if (\n ['contains', 'equals', 'like', 'not_equals'].includes(operator) &&\n (!Array.isArray(relationTo) || !path.endsWith('.relationTo'))\n ) {\n if (typeof relationTo === 'string') {\n const customIDType = payload.collections[relationTo]?.customIDType\n\n if (customIDType) {\n if (customIDType === 'number') {\n formattedValue = parseFloat(val)\n\n if (Number.isNaN(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n }\n } else {\n if (!Types.ObjectId.isValid(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n formattedValue = new Types.ObjectId(formattedValue)\n }\n } else {\n const hasCustomIDType = relationTo.some(\n (relationTo) => !!payload.collections[relationTo]?.customIDType,\n )\n\n if (hasCustomIDType) {\n if (typeof val === 'string') {\n const formattedNumber = Number(val)\n formattedValue = [Types.ObjectId.isValid(val) ? new Types.ObjectId(val) : val]\n formattedOperator = operator === 'not_equals' ? 'not_in' : 'in'\n if (!Number.isNaN(formattedNumber)) {\n formattedValue.push(formattedNumber)\n }\n }\n } else {\n if (!Types.ObjectId.isValid(formattedValue)) {\n return { operator: formattedOperator, val: undefined }\n }\n formattedValue = new Types.ObjectId(formattedValue)\n }\n }\n }\n\n if (\n operator === 'all' &&\n Array.isArray(relationTo) &&\n path.endsWith('.value') &&\n Array.isArray(formattedValue)\n ) {\n formattedValue.forEach((v, i) => {\n if (Types.ObjectId.isValid(v)) {\n formattedValue[i] = new Types.ObjectId(v)\n }\n })\n }\n }\n\n // Set up specific formatting necessary by operators\n\n if (operator === 'near') {\n let lng\n let lat\n let maxDistance\n let minDistance\n\n if (Array.isArray(formattedValue)) {\n ;[lng, lat, maxDistance, minDistance] = formattedValue\n }\n\n if (typeof formattedValue === 'string') {\n ;[lng, lat, maxDistance, minDistance] = createArrayFromCommaDelineated(formattedValue)\n }\n\n if (lng == null || lat == null || (maxDistance == null && minDistance == null)) {\n formattedValue = undefined\n } else {\n formattedValue = {\n $geometry: { type: 'Point', coordinates: [parseFloat(lng), parseFloat(lat)] },\n }\n\n if (maxDistance && !Number.isNaN(Number(maxDistance))) {\n formattedValue.$maxDistance = parseFloat(maxDistance)\n }\n\n if (minDistance && !Number.isNaN(Number(minDistance))) {\n formattedValue.$minDistance = parseFloat(minDistance)\n }\n }\n }\n\n if (operator === 'within' || operator === 'intersects') {\n formattedValue = {\n $geometry: formattedValue,\n }\n }\n\n if (path !== '_id' || (path === '_id' && hasCustomID && field.type === 'text')) {\n if (operator === 'contains' && !Types.ObjectId.isValid(formattedValue)) {\n formattedValue = {\n $options: 'i',\n $regex: formattedValue.replace(/[\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'),\n }\n }\n\n if (operator === 'exists') {\n formattedValue = formattedValue === 'true' || formattedValue === true\n\n let treatEmptyString = !['array', 'blocks', 'checkbox', 'relationship', 'upload'].includes(\n field.type,\n )\n\n if (field.type === 'text' && field.hasMany) {\n treatEmptyString = false\n } else if (field.type === 'number' && field.hasMany) {\n treatEmptyString = false\n } else if (field.type === 'select' && field.hasMany) {\n treatEmptyString = false\n }\n\n // _id can't be empty string, will error Cast to ObjectId failed for value \"\"\n return buildExistsQuery(formattedValue, path, treatEmptyString)\n }\n }\n\n if (\n (path === '_id' || path === 'parent') &&\n operator === 'like' &&\n formattedValue.length === 24 &&\n !hasCustomID\n ) {\n formattedOperator = 'equals'\n }\n\n if (operator === 'exists') {\n formattedValue = formattedValue === 'true' || formattedValue === true\n\n // Clearable fields\n if (['relationship', 'select', 'upload'].includes(field.type)) {\n if (formattedValue) {\n return {\n rawQuery: {\n $and: [{ [path]: { $exists: true } }, { [path]: { $ne: null } }],\n },\n }\n } else {\n return {\n rawQuery: {\n $or: [{ [path]: { $exists: false } }, { [path]: { $eq: null } }],\n },\n }\n }\n }\n }\n\n return { operator: formattedOperator, val: formattedValue }\n}\n"],"names":["Types","createArrayFromCommaDelineated","fieldShouldBeLocalized","buildExistsQuery","formattedValue","path","treatEmptyString","rawQuery","$and","$exists","$ne","$or","$eq","getFieldFromSegments","field","payload","segments","_field","_block","blockReferences","blocks","block","i","length","foundField","flattenedFields","find","each","name","shift","sanitizeQueryValue","hasCustomID","locale","operator","parentIsLocalized","val","formattedOperator","includes","type","split","isValid","ObjectId","undefined","map","id","parsedNumber","parseFloat","Number","isNaN","Array","isArray","reduce","formattedValues","inVal","push","toLowerCase","arrayVal","Boolean","Date","parse","value","relationTo","localizedPath","config","localization","collections","customIDType","some","toString","endsWith","hasCustomIDType","formattedNumber","forEach","v","lng","lat","maxDistance","minDistance","$geometry","coordinates","$maxDistance","$minDistance","$options","$regex","replace","hasMany"],"mappings":"AASA,SAASA,KAAK,QAAQ,WAAU;AAChC,SAASC,8BAA8B,QAAQ,UAAS;AACxD,SAASC,sBAAsB,QAAQ,iBAAgB;AAavD,MAAMC,mBAAmB,CAACC,gBAAyBC,MAAcC,mBAAmB,IAAI;IACtF,IAAIF,gBAAgB;QAClB,OAAO;YACLG,UAAU;gBACRC,MAAM;oBACJ;wBAAE,CAACH,KAAK,EAAE;4BAAEI,SAAS;wBAAK;oBAAE;oBAC5B;wBAAE,CAACJ,KAAK,EAAE;4BAAEK,KAAK;wBAAK;oBAAE;uBACpBJ,mBAAmB;wBAAC;4BAAE,CAACD,KAAK,EAAE;gCAAEK,KAAK;4BAAG;wBAAE;qBAAE,GAAG,EAAE;iBACtD;YACH;QACF;IACF,OAAO;QACL,OAAO;YACLH,UAAU;gBACRI,KAAK;oBACH;wBAAE,CAACN,KAAK,EAAE;4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AA;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,GAAG,SAAS,CA0chE,CAAA"}
|
|
@@ -208,7 +208,8 @@ export const buildJoinAggregation = async ({ adapter, collection, collectionConf
|
|
|
208
208
|
throw new APIError(`Failed to retrieve array of joins for ${slug} in collectio ${collection}`);
|
|
209
209
|
}
|
|
210
210
|
for (const join of joinsList){
|
|
211
|
-
|
|
211
|
+
const projectionPath = versions ? `version.${join.joinPath}` : join.joinPath;
|
|
212
|
+
if (projection && !projection[projectionPath]) {
|
|
212
213
|
continue;
|
|
213
214
|
}
|
|
214
215
|
if (joins?.[join.joinPath] === false) {
|
|
@@ -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[] | undefined> => {\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 if (projection && !projection[join.joinPath]) {\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","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;IACF;IACA,IACE,AAACC,OAAOC,IAAI,CAACR,iBAAiBE,KAAK,EAAEO,MAAM,KAAK,KAC9CT,iBAAiBU,gBAAgB,CAACD,MAAM,IAAI,KAC9CP,UAAU,OACV;QACA;IACF;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,WAAW,EAAEe,QAAQJ;IAEhF,IAAI,CAACM,wBAAwB;QAC3B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pDrC,MAAMF,UAAUxD,UAAU,CAACoC,IAAI;wBAC/B4D,YAAY1F,WAAW,WAAW;wBAClCuD;oBACF;gBACF,GACA;oBACEb,YAAY;wBACV,CAAC,GAAGH,GAAG,KAAK,CAAC,CAAC,EAAE;4BACdyD,MAAM;gCACJzD,IAAI;gCACJ0D,IAAIlB,YAAY,CAAC,YAAY,CAAC,GAAG;gCACjCX,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;oBACT0E,wBAAwBjD,IAAI,GAAGoD,qBAAqBF,cAAc;gBACpE;gBAEA,IAAIzE,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[] | undefined> => {\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;IACF;IACA,IACE,AAACC,OAAOC,IAAI,CAACR,iBAAiBE,KAAK,EAAEO,MAAM,KAAK,KAC9CT,iBAAiBU,gBAAgB,CAACD,MAAM,IAAI,KAC9CP,UAAU,OACV;QACA;IACF;IAEA,MAAMS,aAAab,QAAQc,OAAO,CAACC,WAAW,CAACd,WAAW,EAAEe,QAAQZ;IAEpE,IAAI,CAACS,YAAY;QACf,MAAM,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leTransaction: true;
|
|
7
8
|
transactionOptions: false;
|
|
8
9
|
useJoinAggregations: false;
|
|
9
10
|
usePipelineInSortLookup: false;
|
|
10
11
|
};
|
|
11
12
|
documentdb: {
|
|
13
|
+
bulkOperationsSingleTransaction: true;
|
|
12
14
|
disableIndexHints: true;
|
|
13
15
|
useJoinAggregations: false;
|
|
14
16
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compatibilityOptions.d.ts","sourceRoot":"","sources":["../../src/utilities/compatibilityOptions.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,eAAO,MAAM,oBAAoB
|
|
1
|
+
{"version":3,"file":"compatibilityOptions.d.ts","sourceRoot":"","sources":["../../src/utilities/compatibilityOptions.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;CAqBQ,CAAA"}
|
|
@@ -3,11 +3,13 @@
|
|
|
3
3
|
* is the recommended `mongooseAdapter` settings for compatibility.
|
|
4
4
|
*/ export const compatibilityOptions = {
|
|
5
5
|
cosmosdb: {
|
|
6
|
+
bulkOperationsSingleTransaction: true,
|
|
6
7
|
transactionOptions: false,
|
|
7
8
|
useJoinAggregations: false,
|
|
8
9
|
usePipelineInSortLookup: false
|
|
9
10
|
},
|
|
10
11
|
documentdb: {
|
|
12
|
+
bulkOperationsSingleTransaction: true,
|
|
11
13
|
disableIndexHints: true,
|
|
12
14
|
useJoinAggregations: false
|
|
13
15
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utilities/compatibilityOptions.ts"],"sourcesContent":["import type { Args } from '../index.js'\n\n/**\n * Each key is a mongo-compatible database and the value\n * is the recommended `mongooseAdapter` settings for compatibility.\n */\nexport const compatibilityOptions = {\n cosmosdb: {\n transactionOptions: false,\n useJoinAggregations: false,\n usePipelineInSortLookup: false,\n },\n documentdb: {\n disableIndexHints: true,\n useJoinAggregations: false,\n },\n firestore: {\n disableIndexHints: true,\n ensureIndexes: false,\n transactionOptions: false,\n useAlternativeDropDatabase: true,\n useBigIntForNumberIDs: true,\n useJoinAggregations: false,\n usePipelineInSortLookup: false,\n },\n} satisfies Record<string, Partial<Args>>\n"],"names":["compatibilityOptions","cosmosdb","transactionOptions","useJoinAggregations","usePipelineInSortLookup","documentdb","disableIndexHints","firestore","ensureIndexes","useAlternativeDropDatabase","useBigIntForNumberIDs"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,uBAAuB;IAClCC,UAAU;QACRC,oBAAoB;QACpBC,qBAAqB;QACrBC,yBAAyB;IAC3B;IACAC,YAAY;
|
|
1
|
+
{"version":3,"sources":["../../src/utilities/compatibilityOptions.ts"],"sourcesContent":["import type { Args } from '../index.js'\n\n/**\n * Each key is a mongo-compatible database and the value\n * is the recommended `mongooseAdapter` settings for compatibility.\n */\nexport const compatibilityOptions = {\n cosmosdb: {\n bulkOperationsSingleTransaction: true,\n transactionOptions: false,\n useJoinAggregations: false,\n usePipelineInSortLookup: false,\n },\n documentdb: {\n bulkOperationsSingleTransaction: true,\n disableIndexHints: true,\n useJoinAggregations: false,\n },\n firestore: {\n disableIndexHints: true,\n ensureIndexes: false,\n transactionOptions: false,\n useAlternativeDropDatabase: true,\n useBigIntForNumberIDs: true,\n useJoinAggregations: false,\n usePipelineInSortLookup: false,\n },\n} satisfies Record<string, Partial<Args>>\n"],"names":["compatibilityOptions","cosmosdb","bulkOperationsSingleTransaction","transactionOptions","useJoinAggregations","usePipelineInSortLookup","documentdb","disableIndexHints","firestore","ensureIndexes","useAlternativeDropDatabase","useBigIntForNumberIDs"],"mappings":"AAEA;;;CAGC,GACD,OAAO,MAAMA,uBAAuB;IAClCC,UAAU;QACRC,iCAAiC;QACjCC,oBAAoB;QACpBC,qBAAqB;QACrBC,yBAAyB;IAC3B;IACAC,YAAY;QACVJ,iCAAiC;QACjCK,mBAAmB;QACnBH,qBAAqB;IACvB;IACAI,WAAW;QACTD,mBAAmB;QACnBE,eAAe;QACfN,oBAAoB;QACpBO,4BAA4B;QAC5BC,uBAAuB;QACvBP,qBAAqB;QACrBC,yBAAyB;IAC3B;AACF,EAAyC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@payloadcms/db-mongodb",
|
|
3
|
-
"version": "3.71.0
|
|
3
|
+
"version": "3.71.0",
|
|
4
4
|
"description": "The officially supported MongoDB database adapter for Payload",
|
|
5
5
|
"homepage": "https://payloadcms.com",
|
|
6
6
|
"repository": {
|
|
@@ -55,10 +55,10 @@
|
|
|
55
55
|
"mongodb": "6.16.0",
|
|
56
56
|
"mongodb-memory-server": "10.1.4",
|
|
57
57
|
"@payloadcms/eslint-config": "3.28.0",
|
|
58
|
-
"payload": "3.71.0
|
|
58
|
+
"payload": "3.71.0"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"payload": "3.71.0
|
|
61
|
+
"payload": "3.71.0"
|
|
62
62
|
},
|
|
63
63
|
"scripts": {
|
|
64
64
|
"build": "pnpm build:types && pnpm build:swc",
|