@payloadcms/db-mongodb 3.48.0-canary.5 → 3.48.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.
Files changed (48) hide show
  1. package/dist/connect.d.ts.map +1 -1
  2. package/dist/connect.js +17 -0
  3. package/dist/connect.js.map +1 -1
  4. package/dist/find.d.ts.map +1 -1
  5. package/dist/find.js +10 -0
  6. package/dist/find.js.map +1 -1
  7. package/dist/findDistinct.d.ts +3 -0
  8. package/dist/findDistinct.d.ts.map +1 -0
  9. package/dist/findDistinct.js +122 -0
  10. package/dist/findDistinct.js.map +1 -0
  11. package/dist/findOne.d.ts.map +1 -1
  12. package/dist/findOne.js +12 -0
  13. package/dist/findOne.js.map +1 -1
  14. package/dist/index.d.ts +32 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +9 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/models/buildSchema.d.ts.map +1 -1
  19. package/dist/models/buildSchema.js +6 -2
  20. package/dist/models/buildSchema.js.map +1 -1
  21. package/dist/queries/buildSortParam.d.ts.map +1 -1
  22. package/dist/queries/buildSortParam.js +35 -13
  23. package/dist/queries/buildSortParam.js.map +1 -1
  24. package/dist/queryDrafts.d.ts.map +1 -1
  25. package/dist/queryDrafts.js +11 -0
  26. package/dist/queryDrafts.js.map +1 -1
  27. package/dist/updateOne.d.ts.map +1 -1
  28. package/dist/updateOne.js +11 -2
  29. package/dist/updateOne.js.map +1 -1
  30. package/dist/utilities/aggregatePaginate.d.ts.map +1 -1
  31. package/dist/utilities/aggregatePaginate.js +4 -2
  32. package/dist/utilities/aggregatePaginate.js.map +1 -1
  33. package/dist/utilities/buildJoinAggregation.d.ts.map +1 -1
  34. package/dist/utilities/buildJoinAggregation.js +3 -0
  35. package/dist/utilities/buildJoinAggregation.js.map +1 -1
  36. package/dist/utilities/compatabilityOptions.d.ts +24 -0
  37. package/dist/utilities/compatabilityOptions.d.ts.map +1 -0
  38. package/dist/utilities/compatabilityOptions.js +24 -0
  39. package/dist/utilities/compatabilityOptions.js.map +1 -0
  40. package/dist/utilities/resolveJoins.d.ts +25 -0
  41. package/dist/utilities/resolveJoins.d.ts.map +1 -0
  42. package/dist/utilities/resolveJoins.js +469 -0
  43. package/dist/utilities/resolveJoins.js.map +1 -0
  44. package/dist/utilities/transform.d.ts +2 -1
  45. package/dist/utilities/transform.d.ts.map +1 -1
  46. package/dist/utilities/transform.js +14 -2
  47. package/dist/utilities/transform.js.map +1 -1
  48. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAOtC,eAAO,MAAM,OAAO,EAAE,OA+ErB,CAAA"}
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAA;AAOtC,eAAO,MAAM,OAAO,EAAE,OAkGrB,CAAA"}
package/dist/connect.js CHANGED
@@ -21,6 +21,23 @@ export const connect = async function connect(options = {
21
21
  }
22
22
  try {
23
23
  this.connection = (await mongoose.connect(urlToConnect, connectionOptions)).connection;
24
+ if (this.useAlternativeDropDatabase) {
25
+ if (this.connection.db) {
26
+ // Firestore doesn't support dropDatabase, so we monkey patch
27
+ // dropDatabase to delete all documents from all collections instead
28
+ this.connection.db.dropDatabase = async function() {
29
+ const existingCollections = await this.listCollections().toArray();
30
+ await Promise.all(existingCollections.map(async (collectionInfo)=>{
31
+ const collection = this.collection(collectionInfo.name);
32
+ await collection.deleteMany({});
33
+ }));
34
+ return true;
35
+ };
36
+ this.connection.dropDatabase = async function() {
37
+ await this.db?.dropDatabase();
38
+ };
39
+ }
40
+ }
24
41
  // If we are running a replica set with MongoDB Memory Server,
25
42
  // wait until the replica set elects a primary before proceeding
26
43
  if (this.mongoMemoryServer) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { defaultBeginTransaction } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nexport const connect: Connect = async function connect(\n this: MongooseAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n if (this.url === false) {\n return\n }\n\n if (typeof this.url !== 'string') {\n throw new Error('Error: missing MongoDB connection URL.')\n }\n\n const urlToConnect = this.url\n\n const connectionOptions: { useFacet: undefined } & ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n useFacet: undefined,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n this.connection = (await mongoose.connect(urlToConnect, connectionOptions)).connection\n\n // If we are running a replica set with MongoDB Memory Server,\n // wait until the replica set elects a primary before proceeding\n if (this.mongoMemoryServer) {\n this.payload.logger.info(\n 'Waiting for MongoDB Memory Server replica set to elect a primary...',\n )\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n const client = this.connection.getClient()\n\n if (!client.options.replicaSet) {\n this.transactionOptions = false\n this.beginTransaction = defaultBeginTransaction()\n }\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info('---- DROPPING DATABASE ----')\n await mongoose.connection.dropDatabase()\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n this.payload.config.collections.map(async (coll) => {\n await this.collections[coll.slug]?.ensureIndexes()\n }),\n )\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations })\n }\n } catch (err) {\n let msg = `Error: cannot connect to MongoDB.`\n\n if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {\n msg = `${msg} Details: ${err.message}`\n }\n\n this.payload.logger.error({\n err,\n msg,\n })\n process.exit(1)\n }\n}\n"],"names":["mongoose","defaultBeginTransaction","connect","options","hotReload","url","Error","urlToConnect","connectionOptions","autoIndex","connectOptions","useFacet","undefined","connection","mongoMemoryServer","payload","logger","info","Promise","resolve","setTimeout","client","getClient","replicaSet","transactionOptions","beginTransaction","process","env","PAYLOAD_DROP_DATABASE","dropDatabase","ensureIndexes","all","config","collections","map","coll","slug","NODE_ENV","prodMigrations","migrate","migrations","err","msg","message","error","exit"],"mappings":"AAGA,OAAOA,cAAc,WAAU;AAC/B,SAASC,uBAAuB,QAAQ,UAAS;AAIjD,OAAO,MAAMC,UAAmB,eAAeA,QAE7CC,UAAU;IACRC,WAAW;AACb,CAAC;IAED,MAAM,EAAEA,SAAS,EAAE,GAAGD;IAEtB,IAAI,IAAI,CAACE,GAAG,KAAK,OAAO;QACtB;IACF;IAEA,IAAI,OAAO,IAAI,CAACA,GAAG,KAAK,UAAU;QAChC,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,eAAe,IAAI,CAACF,GAAG;IAE7B,MAAMG,oBAA8D;QAClEC,WAAW;QACX,GAAG,IAAI,CAACC,cAAc;QACtBC,UAAUC;IACZ;IAEA,IAAIR,WAAW;QACbI,kBAAkBC,SAAS,GAAG;IAChC;IAEA,IAAI;QACF,IAAI,CAACI,UAAU,GAAG,AAAC,CAAA,MAAMb,SAASE,OAAO,CAACK,cAAcC,kBAAiB,EAAGK,UAAU;QAEtF,8DAA8D;QAC9D,gEAAgE;QAChE,IAAI,IAAI,CAACC,iBAAiB,EAAE;YAC1B,IAAI,CAACC,OAAO,CAACC,MAAM,CAACC,IAAI,CACtB;YAEF,MAAM,IAAIC,QAAQ,CAACC,UAAYC,WAAWD,SAAS;QACrD;QAEA,MAAME,SAAS,IAAI,CAACR,UAAU,CAACS,SAAS;QAExC,IAAI,CAACD,OAAOlB,OAAO,CAACoB,UAAU,EAAE;YAC9B,IAAI,CAACC,kBAAkB,GAAG;YAC1B,IAAI,CAACC,gBAAgB,GAAGxB;QAC1B;QAEA,IAAI,CAACG,WAAW;YACd,IAAIsB,QAAQC,GAAG,CAACC,qBAAqB,KAAK,QAAQ;gBAChD,IAAI,CAACb,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC;gBACzB,MAAMjB,SAASa,UAAU,CAACgB,YAAY;gBACtC,IAAI,CAACd,OAAO,CAACC,MAAM,CAACC,IAAI,CAAC;YAC3B;QACF;QAEA,IAAI,IAAI,CAACa,aAAa,EAAE;YACtB,MAAMZ,QAAQa,GAAG,CACf,IAAI,CAAChB,OAAO,CAACiB,MAAM,CAACC,WAAW,CAACC,GAAG,CAAC,OAAOC;gBACzC,MAAM,IAAI,CAACF,WAAW,CAACE,KAAKC,IAAI,CAAC,EAAEN;YACrC;QAEJ;QAEA,IAAIJ,QAAQC,GAAG,CAACU,QAAQ,KAAK,gBAAgB,IAAI,CAACC,cAAc,EAAE;YAChE,MAAM,IAAI,CAACC,OAAO,CAAC;gBAAEC,YAAY,IAAI,CAACF,cAAc;YAAC;QACvD;IACF,EAAE,OAAOG,KAAK;QACZ,IAAIC,MAAM,CAAC,iCAAiC,CAAC;QAE7C,IAAI,OAAOD,QAAQ,YAAYA,OAAO,aAAaA,OAAO,OAAOA,IAAIE,OAAO,KAAK,UAAU;YACzFD,MAAM,GAAGA,IAAI,UAAU,EAAED,IAAIE,OAAO,EAAE;QACxC;QAEA,IAAI,CAAC5B,OAAO,CAACC,MAAM,CAAC4B,KAAK,CAAC;YACxBH;YACAC;QACF;QACAhB,QAAQmB,IAAI,CAAC;IACf;AACF,EAAC"}
1
+ {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect } from 'payload'\n\nimport mongoose from 'mongoose'\nimport { defaultBeginTransaction } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nexport const connect: Connect = async function connect(\n this: MongooseAdapter,\n options = {\n hotReload: false,\n },\n) {\n const { hotReload } = options\n\n if (this.url === false) {\n return\n }\n\n if (typeof this.url !== 'string') {\n throw new Error('Error: missing MongoDB connection URL.')\n }\n\n const urlToConnect = this.url\n\n const connectionOptions: { useFacet: undefined } & ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n useFacet: undefined,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n this.connection = (await mongoose.connect(urlToConnect, connectionOptions)).connection\n if (this.useAlternativeDropDatabase) {\n if (this.connection.db) {\n // Firestore doesn't support dropDatabase, so we monkey patch\n // dropDatabase to delete all documents from all collections instead\n this.connection.db.dropDatabase = async function (): Promise<boolean> {\n const existingCollections = await this.listCollections().toArray()\n await Promise.all(\n existingCollections.map(async (collectionInfo) => {\n const collection = this.collection(collectionInfo.name)\n await collection.deleteMany({})\n }),\n )\n return true\n }\n this.connection.dropDatabase = async function () {\n await this.db?.dropDatabase()\n }\n }\n }\n\n // If we are running a replica set with MongoDB Memory Server,\n // wait until the replica set elects a primary before proceeding\n if (this.mongoMemoryServer) {\n this.payload.logger.info(\n 'Waiting for MongoDB Memory Server replica set to elect a primary...',\n )\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n const client = this.connection.getClient()\n\n if (!client.options.replicaSet) {\n this.transactionOptions = false\n this.beginTransaction = defaultBeginTransaction()\n }\n\n if (!hotReload) {\n if (process.env.PAYLOAD_DROP_DATABASE === 'true') {\n this.payload.logger.info('---- DROPPING DATABASE ----')\n await mongoose.connection.dropDatabase()\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n this.payload.config.collections.map(async (coll) => {\n await this.collections[coll.slug]?.ensureIndexes()\n }),\n )\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations })\n }\n } catch (err) {\n let msg = `Error: cannot connect to MongoDB.`\n\n if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {\n msg = `${msg} Details: ${err.message}`\n }\n\n this.payload.logger.error({\n err,\n msg,\n })\n process.exit(1)\n }\n}\n"],"names":["mongoose","defaultBeginTransaction","connect","options","hotReload","url","Error","urlToConnect","connectionOptions","autoIndex","connectOptions","useFacet","undefined","connection","useAlternativeDropDatabase","db","dropDatabase","existingCollections","listCollections","toArray","Promise","all","map","collectionInfo","collection","name","deleteMany","mongoMemoryServer","payload","logger","info","resolve","setTimeout","client","getClient","replicaSet","transactionOptions","beginTransaction","process","env","PAYLOAD_DROP_DATABASE","ensureIndexes","config","collections","coll","slug","NODE_ENV","prodMigrations","migrate","migrations","err","msg","message","error","exit"],"mappings":"AAGA,OAAOA,cAAc,WAAU;AAC/B,SAASC,uBAAuB,QAAQ,UAAS;AAIjD,OAAO,MAAMC,UAAmB,eAAeA,QAE7CC,UAAU;IACRC,WAAW;AACb,CAAC;IAED,MAAM,EAAEA,SAAS,EAAE,GAAGD;IAEtB,IAAI,IAAI,CAACE,GAAG,KAAK,OAAO;QACtB;IACF;IAEA,IAAI,OAAO,IAAI,CAACA,GAAG,KAAK,UAAU;QAChC,MAAM,IAAIC,MAAM;IAClB;IAEA,MAAMC,eAAe,IAAI,CAACF,GAAG;IAE7B,MAAMG,oBAA8D;QAClEC,WAAW;QACX,GAAG,IAAI,CAACC,cAAc;QACtBC,UAAUC;IACZ;IAEA,IAAIR,WAAW;QACbI,kBAAkBC,SAAS,GAAG;IAChC;IAEA,IAAI;QACF,IAAI,CAACI,UAAU,GAAG,AAAC,CAAA,MAAMb,SAASE,OAAO,CAACK,cAAcC,kBAAiB,EAAGK,UAAU;QACtF,IAAI,IAAI,CAACC,0BAA0B,EAAE;YACnC,IAAI,IAAI,CAACD,UAAU,CAACE,EAAE,EAAE;gBACtB,6DAA6D;gBAC7D,oEAAoE;gBACpE,IAAI,CAACF,UAAU,CAACE,EAAE,CAACC,YAAY,GAAG;oBAChC,MAAMC,sBAAsB,MAAM,IAAI,CAACC,eAAe,GAAGC,OAAO;oBAChE,MAAMC,QAAQC,GAAG,CACfJ,oBAAoBK,GAAG,CAAC,OAAOC;wBAC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AIC,MAAM,CAAC,iCAAiC,CAAC;QAE7C,IAAI,OAAOD,QAAQ,YAAYA,OAAO,aAAaA,OAAO,OAAOA,IAAIE,OAAO,KAAK,UAAU;YACzFD,MAAM,GAAGA,IAAI,UAAU,EAAED,IAAIE,OAAO,EAAE;QACxC;QAEA,IAAI,CAACxB,OAAO,CAACC,MAAM,CAACwB,KAAK,CAAC;YACxBH;YACAC;QACF;QACAb,QAAQgB,IAAI,CAAC;IACf;AACF,EAAC"}
@@ -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;AAenC,eAAO,MAAM,IAAI,EAAE,IAqJlB,CAAA"}
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,IA+JlB,CAAA"}
package/dist/find.js CHANGED
@@ -6,6 +6,7 @@ import { buildJoinAggregation } from './utilities/buildJoinAggregation.js';
6
6
  import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js';
7
7
  import { getCollection } from './utilities/getEntity.js';
8
8
  import { getSession } from './utilities/getSession.js';
9
+ import { resolveJoins } from './utilities/resolveJoins.js';
9
10
  import { transform } from './utilities/transform.js';
10
11
  export const find = async function find({ collection: collectionSlug, draftsEnabled, joins = {}, limit = 0, locale, page, pagination, projection, req, select, sort: sortArg, where = {} }) {
11
12
  const { collectionConfig, Model } = getCollection({
@@ -118,6 +119,15 @@ export const find = async function find({ collection: collectionSlug, draftsEnab
118
119
  } else {
119
120
  result = await Model.paginate(query, paginationOptions);
120
121
  }
122
+ if (!this.useJoinAggregations) {
123
+ await resolveJoins({
124
+ adapter: this,
125
+ collectionSlug,
126
+ docs: result.docs,
127
+ joins,
128
+ locale
129
+ });
130
+ }
121
131
  transform({
122
132
  adapter: this,
123
133
  data: result.docs,
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 { 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 const session = await getSession(this, req)\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: true,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\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 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 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","transform","find","collection","collectionSlug","draftsEnabled","joins","limit","locale","page","pagination","projection","req","select","sort","sortArg","where","collectionConfig","Model","adapter","session","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","useEstimatedCount","length","paginationOptions","lean","leanWithId","options","collation","defaultLocale","disableIndexHints","useCustomCountFn","Promise","resolve","countDocuments","hint","_id","result","aggregate","joinAggregation","undefined","paginate","data","docs","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,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,GAAGnB,cAAc;QAAEoB,SAAS,IAAI;QAAEf;IAAe;IAElF,MAAMgB,UAAU,MAAMpB,WAAW,IAAI,EAAEY;IAEvC,IAAIS,oBAAoB;IAExB,IAAIL,OAAO;QACT,MAAMM,cAAc7B,wBAAwBuB;QAC5CK,oBAAoBC,YAAYC,IAAI,CAAC,CAACC,OAASC,OAAOC,IAAI,CAACF,MAAMD,IAAI,CAAC,CAACI,MAAQA,QAAQ;IACzF;IAEA,MAAMC,kBAAmC,EAAE;IAE3C,IAAId;IACJ,IAAI,CAACO,mBAAmB;QACtBP,OAAOnB,eAAe;YACpBwB,SAAS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EnC,mCAAmC;QACnC,IAAIA,UAAU,GAAG;YACf+B,kBAAkB5B,UAAU,GAAG;QACjC;IACF;IAEA,IAAIyC;IAEJ,MAAMC,YAAY,MAAMvD,qBAAqB;QAC3CsB,SAAS,IAAI;QACbhB,YAAYC;QACZa;QACAZ;QACAC;QACAE;QACA2B;IACF;IAEA,IAAIiB,aAAaxB,gBAAgBS,MAAM,GAAG,GAAG;QAC3Cc,SAAS,MAAMvD,kBAAkB;YAC/BuB,SAAS,IAAI;YACbuB,WAAWJ,kBAAkBI,SAAS;YACtCW,iBAAiBD;YACjB7C,OAAO+B,kBAAkB/B,KAAK;YAC9BW;YACAT,MAAM6B,kBAAkB7B,IAAI;YAC5BC,YAAY4B,kBAAkB5B,UAAU;YACxCC,YAAY2B,kBAAkB3B,UAAU;YACxCwB;YACAf,SAASkB,kBAAkBG,OAAO,EAAErB,WAAWkC;YAC/CxC,MAAMwB,kBAAkBxB,IAAI;YAC5Bc;YACAQ,mBAAmBE,kBAAkBF,iBAAiB;QACxD;IACF,OAAO;QACLe,SAAS,MAAMjC,MAAMqC,QAAQ,CAACpB,OAAOG;IACvC;IAEArC,UAAU;QACRkB,SAAS,IAAI;QACbqC,MAAML,OAAOM,IAAI;QACjB1B,QAAQd,iBAAiBc,MAAM;QAC/B2B,WAAW;IACb;IAEA,OAAOP;AACT,EAAC"}
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 const session = await getSession(this, req)\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: true,\n })\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\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 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","session","hasNearConstraint","constraints","some","prop","Object","keys","key","sortAggregation","config","payload","fields","flattenedFields","defaultSort","timestamps","query","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,0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AMxD,kBAAkB;YAC/BwB,SAAS,IAAI;YACbuB,WAAWJ,kBAAkBI,SAAS;YACtCW,iBAAiBD;YACjB7C,OAAO+B,kBAAkB/B,KAAK;YAC9BW;YACAT,MAAM6B,kBAAkB7B,IAAI;YAC5BC,YAAY4B,kBAAkB5B,UAAU;YACxCC,YAAY2B,kBAAkB3B,UAAU;YACxCwB;YACAf,SAASkB,kBAAkBG,OAAO,EAAErB,WAAWkC;YAC/CxC,MAAMwB,kBAAkBxB,IAAI;YAC5Bc;YACAQ,mBAAmBE,kBAAkBF,iBAAiB;QACxD;IACF,OAAO;QACLe,SAAS,MAAMjC,MAAMqC,QAAQ,CAACpB,OAAOG;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;QACjB1B,QAAQd,iBAAiBc,MAAM;QAC/B4B,WAAW;IACb;IAEA,OAAOR;AACT,EAAC"}
@@ -0,0 +1,3 @@
1
+ import { type FindDistinct } from 'payload';
2
+ export declare const findDistinct: FindDistinct;
3
+ //# sourceMappingURL=findDistinct.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"findDistinct.d.ts","sourceRoot":"","sources":["../src/findDistinct.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,YAAY,EAAkB,MAAM,SAAS,CAAA;AAS3D,eAAO,MAAM,YAAY,EAAE,YAiI1B,CAAA"}
@@ -0,0 +1,122 @@
1
+ import { getFieldByPath } from 'payload';
2
+ import { buildQuery } from './queries/buildQuery.js';
3
+ import { buildSortParam } from './queries/buildSortParam.js';
4
+ import { getCollection } from './utilities/getEntity.js';
5
+ import { getSession } from './utilities/getSession.js';
6
+ export const findDistinct = async function(args) {
7
+ const { collectionConfig, Model } = getCollection({
8
+ adapter: this,
9
+ collectionSlug: args.collection
10
+ });
11
+ const session = await getSession(this, args.req);
12
+ const { where = {} } = args;
13
+ const sortAggregation = [];
14
+ const sort = buildSortParam({
15
+ adapter: this,
16
+ config: this.payload.config,
17
+ fields: collectionConfig.flattenedFields,
18
+ locale: args.locale,
19
+ sort: args.sort ?? args.field,
20
+ sortAggregation,
21
+ timestamps: true
22
+ });
23
+ const query = await buildQuery({
24
+ adapter: this,
25
+ collectionSlug: args.collection,
26
+ fields: collectionConfig.flattenedFields,
27
+ locale: args.locale,
28
+ where
29
+ });
30
+ const fieldPathResult = getFieldByPath({
31
+ fields: collectionConfig.flattenedFields,
32
+ path: args.field
33
+ });
34
+ let fieldPath = args.field;
35
+ if (fieldPathResult?.pathHasLocalized && args.locale) {
36
+ fieldPath = fieldPathResult.localizedPath.replace('<locale>', args.locale);
37
+ }
38
+ const page = args.page || 1;
39
+ const sortProperty = Object.keys(sort)[0]// assert because buildSortParam always returns at least 1 key.
40
+ ;
41
+ const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1;
42
+ const pipeline = [
43
+ {
44
+ $match: query
45
+ },
46
+ ...sortAggregation.length > 0 ? sortAggregation : [],
47
+ {
48
+ $group: {
49
+ _id: {
50
+ _field: `$${fieldPath}`,
51
+ ...sortProperty === fieldPath ? {} : {
52
+ _sort: `$${sortProperty}`
53
+ }
54
+ }
55
+ }
56
+ },
57
+ {
58
+ $sort: {
59
+ [sortProperty === fieldPath ? '_id._field' : '_id._sort']: sortDirection
60
+ }
61
+ }
62
+ ];
63
+ const getValues = async ()=>{
64
+ return Model.aggregate(pipeline, {
65
+ session
66
+ }).then((res)=>res.map((each)=>({
67
+ [args.field]: JSON.parse(JSON.stringify(each._id._field))
68
+ })));
69
+ };
70
+ if (args.limit) {
71
+ pipeline.push({
72
+ $skip: (page - 1) * args.limit
73
+ });
74
+ pipeline.push({
75
+ $limit: args.limit
76
+ });
77
+ const totalDocs = await Model.aggregate([
78
+ {
79
+ $match: query
80
+ },
81
+ {
82
+ $group: {
83
+ _id: `$${fieldPath}`
84
+ }
85
+ },
86
+ {
87
+ $count: 'count'
88
+ }
89
+ ], {
90
+ session
91
+ }).then((res)=>res[0]?.count ?? 0);
92
+ const totalPages = Math.ceil(totalDocs / args.limit);
93
+ const hasPrevPage = page > 1;
94
+ const hasNextPage = totalPages > page;
95
+ const pagingCounter = (page - 1) * args.limit + 1;
96
+ return {
97
+ hasNextPage,
98
+ hasPrevPage,
99
+ limit: args.limit,
100
+ nextPage: hasNextPage ? page + 1 : null,
101
+ page,
102
+ pagingCounter,
103
+ prevPage: hasPrevPage ? page - 1 : null,
104
+ totalDocs,
105
+ totalPages,
106
+ values: await getValues()
107
+ };
108
+ }
109
+ const values = await getValues();
110
+ return {
111
+ hasNextPage: false,
112
+ hasPrevPage: false,
113
+ limit: 0,
114
+ page: 1,
115
+ pagingCounter: 1,
116
+ totalDocs: values.length,
117
+ totalPages: 1,
118
+ values
119
+ };
120
+ };
121
+
122
+ //# sourceMappingURL=findDistinct.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/findDistinct.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\n\nimport { type FindDistinct, getFieldByPath } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.js'\nimport { buildSortParam } from './queries/buildSortParam.js'\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\n\nexport const findDistinct: FindDistinct = async function (this: MongooseAdapter, args) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug: args.collection,\n })\n\n const session = await getSession(this, args.req)\n\n const { where = {} } = args\n\n const sortAggregation: PipelineStage[] = []\n\n const sort = buildSortParam({\n adapter: this,\n config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n sort: args.sort ?? args.field,\n sortAggregation,\n timestamps: true,\n })\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug: args.collection,\n fields: collectionConfig.flattenedFields,\n locale: args.locale,\n where,\n })\n\n const fieldPathResult = getFieldByPath({\n fields: collectionConfig.flattenedFields,\n path: args.field,\n })\n let fieldPath = args.field\n if (fieldPathResult?.pathHasLocalized && args.locale) {\n fieldPath = fieldPathResult.localizedPath.replace('<locale>', args.locale)\n }\n\n const page = args.page || 1\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 pipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n\n {\n $group: {\n _id: {\n _field: `$${fieldPath}`,\n ...(sortProperty === fieldPath\n ? {}\n : {\n _sort: `$${sortProperty}`,\n }),\n },\n },\n },\n {\n $sort: {\n [sortProperty === fieldPath ? '_id._field' : '_id._sort']: sortDirection,\n },\n },\n ]\n\n const getValues = async () => {\n return Model.aggregate(pipeline, { session }).then((res) =>\n res.map((each) => ({\n [args.field]: JSON.parse(JSON.stringify(each._id._field)),\n })),\n )\n }\n\n if (args.limit) {\n pipeline.push({\n $skip: (page - 1) * args.limit,\n })\n pipeline.push({ $limit: args.limit })\n const totalDocs = await Model.aggregate(\n [\n {\n $match: query,\n },\n {\n $group: {\n _id: `$${fieldPath}`,\n },\n },\n { $count: 'count' },\n ],\n {\n session,\n },\n ).then((res) => res[0]?.count ?? 0)\n const totalPages = Math.ceil(totalDocs / args.limit)\n const hasPrevPage = page > 1\n const hasNextPage = totalPages > page\n const pagingCounter = (page - 1) * args.limit + 1\n\n return {\n hasNextPage,\n hasPrevPage,\n limit: args.limit,\n nextPage: hasNextPage ? page + 1 : null,\n page,\n pagingCounter,\n prevPage: hasPrevPage ? page - 1 : null,\n totalDocs,\n totalPages,\n values: await getValues(),\n }\n }\n\n const values = await getValues()\n\n return {\n hasNextPage: false,\n hasPrevPage: false,\n limit: 0,\n page: 1,\n pagingCounter: 1,\n totalDocs: values.length,\n totalPages: 1,\n values,\n }\n}\n"],"names":["getFieldByPath","buildQuery","buildSortParam","getCollection","getSession","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","session","req","where","sortAggregation","sort","config","payload","fields","flattenedFields","locale","field","timestamps","query","fieldPathResult","path","fieldPath","pathHasLocalized","localizedPath","replace","page","sortProperty","Object","keys","sortDirection","pipeline","$match","length","$group","_id","_field","_sort","$sort","getValues","aggregate","then","res","map","each","JSON","parse","stringify","limit","push","$skip","$limit","totalDocs","$count","count","totalPages","Math","ceil","hasPrevPage","hasNextPage","pagingCounter","nextPage","prevPage","values"],"mappings":"AAEA,SAA4BA,cAAc,QAAQ,UAAS;AAI3D,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,OAAO,MAAMC,eAA6B,eAAuCC,IAAI;IACnF,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGL,cAAc;QAChDM,SAAS,IAAI;QACbC,gBAAgBJ,KAAKK,UAAU;IACjC;IAEA,MAAMC,UAAU,MAAMR,WAAW,IAAI,EAAEE,KAAKO,GAAG;IAE/C,MAAM,EAAEC,QAAQ,CAAC,CAAC,EAAE,GAAGR;IAEvB,MAAMS,kBAAmC,EAAE;IAE3C,MAAMC,OAAOd,eAAe;QAC1BO,SAAS,IAAI;QACbQ,QAAQ,IAAI,CAACC,OAAO,CAACD,MAAM;QAC3BE,QAAQZ,iBAAiBa,eAAe;QACxCC,QAAQf,KAAKe,MAAM;QACnBL,MAAMV,KAAKU,IAAI,IAAIV,KAAKgB,KAAK;QAC7BP;QACAQ,YAAY;IACd;IAEA,MAAMC,QAAQ,MAAMvB,WAAW;QAC7BQ,SAAS,IAAI;QACbC,gBAAgBJ,KAAKK,UAAU;QAC/BQ,QAAQZ,iBAAiBa,eAAe;QACxCC,QAAQf,KAAKe,MAAM;QACnBP;IACF;IAEA,MAAMW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AAEE,QAAQlD,KAAK+C,KAAK;QAAC;QACnC,MAAMI,YAAY,MAAMjD,MAAMqC,SAAS,CACrC;YACE;gBACER,QAAQb;YACV;YACA;gBACEe,QAAQ;oBACNC,KAAK,CAAC,CAAC,EAAEb,WAAW;gBACtB;YACF;YACA;gBAAE+B,QAAQ;YAAQ;SACnB,EACD;YACE9C;QACF,GACAkC,IAAI,CAAC,CAACC,MAAQA,GAAG,CAAC,EAAE,EAAEY,SAAS;QACjC,MAAMC,aAAaC,KAAKC,IAAI,CAACL,YAAYnD,KAAK+C,KAAK;QACnD,MAAMU,cAAchC,OAAO;QAC3B,MAAMiC,cAAcJ,aAAa7B;QACjC,MAAMkC,gBAAgB,AAAClC,CAAAA,OAAO,CAAA,IAAKzB,KAAK+C,KAAK,GAAG;QAEhD,OAAO;YACLW;YACAD;YACAV,OAAO/C,KAAK+C,KAAK;YACjBa,UAAUF,cAAcjC,OAAO,IAAI;YACnCA;YACAkC;YACAE,UAAUJ,cAAchC,OAAO,IAAI;YACnC0B;YACAG;YACAQ,QAAQ,MAAMxB;QAChB;IACF;IAEA,MAAMwB,SAAS,MAAMxB;IAErB,OAAO;QACLoB,aAAa;QACbD,aAAa;QACbV,OAAO;QACPtB,MAAM;QACNkC,eAAe;QACfR,WAAWW,OAAO9B,MAAM;QACxBsB,YAAY;QACZQ;IACF;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"findOne.d.ts","sourceRoot":"","sources":["../src/findOne.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,SAAS,CAAA;AAYtC,eAAO,MAAM,OAAO,EAAE,OA8DrB,CAAA"}
1
+ {"version":3,"file":"findOne.d.ts","sourceRoot":"","sources":["../src/findOne.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,SAAS,CAAA;AAatC,eAAO,MAAM,OAAO,EAAE,OAwErB,CAAA"}
package/dist/findOne.js CHANGED
@@ -4,6 +4,7 @@ import { buildJoinAggregation } from './utilities/buildJoinAggregation.js';
4
4
  import { buildProjectionFromSelect } from './utilities/buildProjectionFromSelect.js';
5
5
  import { getCollection } from './utilities/getEntity.js';
6
6
  import { getSession } from './utilities/getSession.js';
7
+ import { resolveJoins } from './utilities/resolveJoins.js';
7
8
  import { transform } from './utilities/transform.js';
8
9
  export const findOne = async function findOne({ collection: collectionSlug, draftsEnabled, joins, locale, req, select, where = {} }) {
9
10
  const { collectionConfig, Model } = getCollection({
@@ -55,6 +56,17 @@ export const findOne = async function findOne({ collection: collectionSlug, draf
55
56
  options.projection = projection;
56
57
  doc = await Model.findOne(query, {}, options);
57
58
  }
59
+ if (doc && !this.useJoinAggregations) {
60
+ await resolveJoins({
61
+ adapter: this,
62
+ collectionSlug,
63
+ docs: [
64
+ doc
65
+ ],
66
+ joins,
67
+ locale
68
+ });
69
+ }
58
70
  if (!doc) {
59
71
  return null;
60
72
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/findOne.ts"],"sourcesContent":["import type { AggregateOptions, QueryOptions } from 'mongoose'\n\nimport { type FindOne } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.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 { transform } from './utilities/transform.js'\n\nexport const findOne: FindOne = async function findOne(\n this: MongooseAdapter,\n { collection: collectionSlug, draftsEnabled, joins, locale, req, select, where = {} },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n const session = await getSession(this, req)\n const options: AggregateOptions & QueryOptions = {\n lean: true,\n session,\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n })\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection,\n query,\n })\n\n let doc\n if (aggregate) {\n const { docs } = await aggregatePaginate({\n adapter: this,\n joinAggregation: aggregate,\n limit: 1,\n Model,\n pagination: false,\n projection,\n query,\n session,\n })\n doc = docs[0]\n } else {\n ;(options as Record<string, unknown>).projection = projection\n doc = await Model.findOne(query, {}, options)\n }\n\n if (!doc) {\n return null\n }\n\n transform({ adapter: this, data: doc, fields: collectionConfig.fields, operation: 'read' })\n\n return doc\n}\n"],"names":["buildQuery","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","transform","findOne","collection","collectionSlug","draftsEnabled","joins","locale","req","select","where","collectionConfig","Model","adapter","session","options","lean","query","fields","flattenedFields","projection","aggregate","doc","docs","joinAggregation","limit","pagination","data","operation"],"mappings":"AAMA,SAASA,UAAU,QAAQ,0BAAyB;AACpD,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,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,UAAmB,eAAeA,QAE7C,EAAEC,YAAYC,cAAc,EAAEC,aAAa,EAAEC,KAAK,EAAEC,MAAM,EAAEC,GAAG,EAAEC,MAAM,EAAEC,QAAQ,CAAC,CAAC,EAAE;IAErF,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGb,cAAc;QAAEc,SAAS,IAAI;QAAET;IAAe;IAElF,MAAMU,UAAU,MAAMd,WAAW,IAAI,EAAEQ;IACvC,MAAMO,UAA2C;QAC/CC,MAAM;QACNF;IACF;IAEA,MAAMG,QAAQ,MAAMtB,WAAW;QAC7BkB,SAAS,IAAI;QACbT;QACAc,QAAQP,iBAAiBQ,eAAe;QACxCZ;QACAG;IACF;IAEA,MAAMU,aAAatB,0BAA0B;QAC3Ce,SAAS,IAAI;QACbK,QAAQP,iBAAiBQ,eAAe;QACxCV;IACF;IAEA,MAAMY,YAAY,MAAMxB,qBAAqB;QAC3CgB,SAAS,IAAI;QACbV,YAAYC;QACZO;QACAN;QACAC;QACAC;QACAa;QACAH;IACF;IAEA,IAAIK;IACJ,IAAID,WAAW;QACb,MAAM,EAAEE,IAAI,EAAE,GAAG,MAAM3B,kBAAkB;YACvCiB,SAAS,IAAI;YACbW,iBAAiBH;YACjBI,OAAO;YACPb;YACAc,YAAY;YACZN;YACAH;YACAH;QACF;QACAQ,MAAMC,IAAI,CAAC,EAAE;IACf,OAAO;;QACHR,QAAoCK,UAAU,GAAGA;QACnDE,MAAM,MAAMV,MAAMV,OAAO,CAACe,OAAO,CAAC,GAAGF;IACvC;IAEA,IAAI,CAACO,KAAK;QACR,OAAO;IACT;IAEArB,UAAU;QAAEY,SAAS,IAAI;QAAEc,MAAML;QAAKJ,QAAQP,iBAAiBO,MAAM;QAAEU,WAAW;IAAO;IAEzF,OAAON;AACT,EAAC"}
1
+ {"version":3,"sources":["../src/findOne.ts"],"sourcesContent":["import type { AggregateOptions, QueryOptions } from 'mongoose'\n\nimport { type FindOne } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { buildQuery } from './queries/buildQuery.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 findOne: FindOne = async function findOne(\n this: MongooseAdapter,\n { collection: collectionSlug, draftsEnabled, joins, locale, req, select, where = {} },\n) {\n const { collectionConfig, Model } = getCollection({ adapter: this, collectionSlug })\n\n const session = await getSession(this, req)\n const options: AggregateOptions & QueryOptions = {\n lean: true,\n session,\n }\n\n const query = await buildQuery({\n adapter: this,\n collectionSlug,\n fields: collectionConfig.flattenedFields,\n locale,\n where,\n })\n\n const projection = buildProjectionFromSelect({\n adapter: this,\n fields: collectionConfig.flattenedFields,\n select,\n })\n\n const aggregate = await buildJoinAggregation({\n adapter: this,\n collection: collectionSlug,\n collectionConfig,\n draftsEnabled,\n joins,\n locale,\n projection,\n query,\n })\n\n let doc\n if (aggregate) {\n const { docs } = await aggregatePaginate({\n adapter: this,\n joinAggregation: aggregate,\n limit: 1,\n Model,\n pagination: false,\n projection,\n query,\n session,\n })\n doc = docs[0]\n } else {\n ;(options as Record<string, unknown>).projection = projection\n doc = await Model.findOne(query, {}, options)\n }\n\n if (doc && !this.useJoinAggregations) {\n await resolveJoins({\n adapter: this,\n collectionSlug,\n docs: [doc] as Record<string, unknown>[],\n joins,\n locale,\n })\n }\n\n if (!doc) {\n return null\n }\n\n transform({ adapter: this, data: doc, fields: collectionConfig.fields, operation: 'read' })\n\n return doc\n}\n"],"names":["buildQuery","aggregatePaginate","buildJoinAggregation","buildProjectionFromSelect","getCollection","getSession","resolveJoins","transform","findOne","collection","collectionSlug","draftsEnabled","joins","locale","req","select","where","collectionConfig","Model","adapter","session","options","lean","query","fields","flattenedFields","projection","aggregate","doc","docs","joinAggregation","limit","pagination","useJoinAggregations","data","operation"],"mappings":"AAMA,SAASA,UAAU,QAAQ,0BAAyB;AACpD,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,UAA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AEzF,OAAOP;AACT,EAAC"}
package/dist/index.d.ts CHANGED
@@ -81,6 +81,28 @@ export interface Args {
81
81
  transactionOptions?: false | TransactionOptions;
82
82
  /** The URL to connect to MongoDB or false to start payload and prevent connecting */
83
83
  url: false | string;
84
+ /**
85
+ * Set to `true` to use an alternative `dropDatabase` implementation that calls `collection.deleteMany({})` on every collection instead of sending a raw `dropDatabase` command.
86
+ * Payload only uses `dropDatabase` for testing purposes.
87
+ * @default false
88
+ */
89
+ useAlternativeDropDatabase?: boolean;
90
+ /**
91
+ * Set to `true` to use `BigInt` for custom ID fields of type `'number'`.
92
+ * Useful for databases that don't support `double` or `int32` IDs.
93
+ * @default false
94
+ */
95
+ useBigIntForNumberIDs?: boolean;
96
+ /**
97
+ * Set to `false` to disable join aggregations (which use correlated subqueries) and instead populate join fields via multiple `find` queries.
98
+ * @default true
99
+ */
100
+ useJoinAggregations?: boolean;
101
+ /**
102
+ * Set to `false` to disable the use of `pipeline` in the `$lookup` aggregation in sorting.
103
+ * @default true
104
+ */
105
+ usePipelineInSortLookup?: boolean;
84
106
  }
85
107
  export type MongooseAdapter = {
86
108
  collections: {
@@ -96,6 +118,10 @@ export type MongooseAdapter = {
96
118
  up: (args: MigrateUpArgs) => Promise<void>;
97
119
  }[];
98
120
  sessions: Record<number | string, ClientSession>;
121
+ useAlternativeDropDatabase: boolean;
122
+ useBigIntForNumberIDs: boolean;
123
+ useJoinAggregations: boolean;
124
+ usePipelineInSortLookup: boolean;
99
125
  versions: {
100
126
  [slug: string]: CollectionModel;
101
127
  };
@@ -128,10 +154,15 @@ declare module 'payload' {
128
154
  updateVersion: <T extends TypeWithID = TypeWithID>(args: {
129
155
  options?: QueryOptions;
130
156
  } & UpdateVersionArgs<T>) => Promise<TypeWithVersion<T>>;
157
+ useAlternativeDropDatabase: boolean;
158
+ useBigIntForNumberIDs: boolean;
159
+ useJoinAggregations: boolean;
160
+ usePipelineInSortLookup: boolean;
131
161
  versions: {
132
162
  [slug: string]: CollectionModel;
133
163
  };
134
164
  }
135
165
  }
136
- export declare function mongooseAdapter({ allowAdditionalKeys, allowIDOnCreate, autoPluralization, collectionsSchemaOptions, connectOptions, disableFallbackSort, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, }: Args): DatabaseAdapterObj;
166
+ export declare function mongooseAdapter({ allowAdditionalKeys, allowIDOnCreate, autoPluralization, collectionsSchemaOptions, connectOptions, disableFallbackSort, disableIndexHints, ensureIndexes, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions, url, useAlternativeDropDatabase, useBigIntForNumberIDs, useJoinAggregations, usePipelineInSortLookup, }: Args): DatabaseAdapterObj;
167
+ export { compatabilityOptions } from './utilities/compatabilityOptions.js';
137
168
  //# sourceMappingURL=index.d.ts.map
@@ -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,KAAK,EACV,aAAa,EACb,UAAU,EACV,cAAc,EACd,YAAY,EACZ,aAAa,EACd,MAAM,UAAU,CAAA;AACjB,OAAO,KAAK,EACV,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,SAAS,EAET,UAAU,EACV,eAAe,EACf,gBAAgB,EAChB,uBAAuB,EACvB,aAAa,EACb,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAOhB,OAAO,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAkC9F,YAAY,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAEhE,MAAM,WAAW,IAAI;IACnB;;;;;OAKG;IACH,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B;;;;;;;;;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B,mBAA2B,EAC3B,eAAuB,EACvB,iBAAwB,EACxB,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,CA+E3B;AAED,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAA"}
package/dist/index.js CHANGED
@@ -16,6 +16,7 @@ import { deleteOne } from './deleteOne.js';
16
16
  import { deleteVersions } from './deleteVersions.js';
17
17
  import { destroy } from './destroy.js';
18
18
  import { find } from './find.js';
19
+ import { findDistinct } from './findDistinct.js';
19
20
  import { findGlobal } from './findGlobal.js';
20
21
  import { findGlobalVersions } from './findGlobalVersions.js';
21
22
  import { findOne } from './findOne.js';
@@ -33,7 +34,7 @@ import { updateMany } from './updateMany.js';
33
34
  import { updateOne } from './updateOne.js';
34
35
  import { updateVersion } from './updateVersion.js';
35
36
  import { upsert } from './upsert.js';
36
- export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, collectionsSchemaOptions = {}, connectOptions, disableFallbackSort = false, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url }) {
37
+ export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate = false, autoPluralization = true, collectionsSchemaOptions = {}, connectOptions, disableFallbackSort = false, disableIndexHints = false, ensureIndexes = false, migrationDir: migrationDirArg, mongoMemoryServer, prodMigrations, transactionOptions = {}, url, useAlternativeDropDatabase = false, useBigIntForNumberIDs = false, useJoinAggregations = true, usePipelineInSortLookup = true }) {
37
38
  function adapter({ payload }) {
38
39
  const migrationDir = findMigrationDir(migrationDirArg);
39
40
  mongoose.set('strictQuery', false);
@@ -79,6 +80,7 @@ export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate =
79
80
  destroy,
80
81
  disableFallbackSort,
81
82
  find,
83
+ findDistinct,
82
84
  findGlobal,
83
85
  findGlobalVersions,
84
86
  findOne,
@@ -95,7 +97,11 @@ export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate =
95
97
  updateGlobalVersion,
96
98
  updateOne,
97
99
  updateVersion,
98
- upsert
100
+ upsert,
101
+ useAlternativeDropDatabase,
102
+ useBigIntForNumberIDs,
103
+ useJoinAggregations,
104
+ usePipelineInSortLookup
99
105
  });
100
106
  }
101
107
  return {
@@ -105,6 +111,7 @@ export function mongooseAdapter({ allowAdditionalKeys = false, allowIDOnCreate =
105
111
  init: adapter
106
112
  };
107
113
  }
114
+ export { compatabilityOptions } from './utilities/compatabilityOptions.js';
108
115
  /**
109
116
  * Attempt to find migrations directory.
110
117
  *
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 Migration,\n Payload,\n TypeWithID,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport fs from 'fs'\nimport mongoose from 'mongoose'\nimport path from 'path'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { CollectionModel, GlobalModel, MigrateDownArgs, MigrateUpArgs } 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 { 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 /**\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?: Migration[]\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\nexport type MongooseAdapter = {\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 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 TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n versions: {\n [slug: string]: CollectionModel\n }\n }\n}\n\nexport function mongooseAdapter({\n allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\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}: 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 autoPluralization,\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 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 })\n }\n\n return {\n name: 'mongoose',\n allowIDOnCreate,\n defaultIDType: 'text',\n init: adapter,\n }\n}\n\n/**\n * Attempt to find migrations directory.\n *\n * Checks for the following directories in order:\n * - `migrationDir` argument from Payload config\n * - `src/migrations`\n * - `dist/migrations`\n * - `migrations`\n *\n * Defaults to `src/migrations`\n *\n * @param migrationDir\n * @returns\n */\nfunction findMigrationDir(migrationDir?: string): string {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src/migrations')\n const distDir = path.resolve(cwd, 'dist/migrations')\n const relativeMigrations = path.resolve(cwd, 'migrations')\n\n // Use arg if provided\n if (migrationDir) {\n return migrationDir\n }\n\n // Check other common locations\n if (fs.existsSync(srcDir)) {\n return srcDir\n }\n\n if (fs.existsSync(distDir)) {\n return distDir\n }\n\n if (fs.existsSync(relativeMigrations)) {\n return relativeMigrations\n }\n\n return srcDir\n}\n"],"names":["fs","mongoose","path","createDatabaseAdapter","defaultBeginTransaction","connect","count","countGlobalVersions","countVersions","create","createGlobal","createGlobalVersion","createMigration","createVersion","deleteMany","deleteOne","deleteVersions","destroy","find","findGlobal","findGlobalVersions","findOne","findVersions","init","migrateFresh","queryDrafts","beginTransaction","commitTransaction","rollbackTransaction","updateGlobal","updateGlobalVersion","updateJobs","updateMany","updateOne","updateVersion","upsert","mongooseAdapter","allowAdditionalKeys","allowIDOnCreate","autoPluralization","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","adapter","payload","findMigrationDir","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","cwd","process","srcDir","resolve","distDir","relativeMigrations","existsSync"],"mappings":"AAuBA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,cAAc,WAAU;AAC/B,OAAOC,UAAU,OAAM;AACvB,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,UAAS;AAIxE,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,UAAU,QAAQ,kBAAiB;AAC5C,SAASC,kBAAkB,QAAQ,0BAAyB;AAC5D,SAASC,OAAO,QAAQ,eAAc;AACtC,SAASC,YAAY,QAAQ,oBAAmB;AAChD,SAASC,IAAI,QAAQ,YAAW;AACh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YACAC;YACAC;YACAC;YACAC;YACAC;YACAiD,eAAe;YACfhD;YACAC;YACAC;YACAC;YACAyB;YACAxB;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAqB;YACAkB,aAAa;YACbX;YACAJ;YACAvB;YACAG;YACAC;YACAC;YACAG;YACAC;YACAC;QACF;IACF;IAEA,OAAO;QACLoB,MAAM;QACNjB;QACAwB,eAAe;QACfvC,MAAM4B;IACR;AACF;AAEA;;;;;;;;;;;;;CAaC,GACD,SAASE,iBAAiBR,YAAqB;IAC7C,MAAMmB,MAAMC,QAAQD,GAAG;IACvB,MAAME,SAAShE,KAAKiE,OAAO,CAACH,KAAK;IACjC,MAAMI,UAAUlE,KAAKiE,OAAO,CAACH,KAAK;IAClC,MAAMK,qBAAqBnE,KAAKiE,OAAO,CAACH,KAAK;IAE7C,sBAAsB;IACtB,IAAInB,cAAc;QAChB,OAAOA;IACT;IAEA,+BAA+B;IAC/B,IAAI7C,GAAGsE,UAAU,CAACJ,SAAS;QACzB,OAAOA;IACT;IAEA,IAAIlE,GAAGsE,UAAU,CAACF,UAAU;QAC1B,OAAOA;IACT;IAEA,IAAIpE,GAAGsE,UAAU,CAACD,qBAAqB;QACrC,OAAOA;IACT;IAEA,OAAOH;AACT"}
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 Migration,\n Payload,\n TypeWithID,\n TypeWithVersion,\n UpdateGlobalArgs,\n UpdateGlobalVersionArgs,\n UpdateOneArgs,\n UpdateVersionArgs,\n} from 'payload'\n\nimport fs from 'fs'\nimport mongoose from 'mongoose'\nimport path from 'path'\nimport { createDatabaseAdapter, defaultBeginTransaction } from 'payload'\n\nimport type { CollectionModel, GlobalModel, MigrateDownArgs, MigrateUpArgs } 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 /**\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?: Migration[]\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 * 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 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 TypeWithID = TypeWithID>(\n args: { options?: QueryOptions } & UpdateGlobalVersionArgs<T>,\n ) => Promise<TypeWithVersion<T>>\n\n updateOne: (args: { options?: QueryOptions } & UpdateOneArgs) => Promise<Document>\n updateVersion: <T extends TypeWithID = TypeWithID>(\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 allowAdditionalKeys = false,\n allowIDOnCreate = false,\n autoPluralization = true,\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 autoPluralization,\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 { compatabilityOptions } from './utilities/compatabilityOptions.js'\n\n/**\n * Attempt to find migrations directory.\n *\n * Checks for the following directories in order:\n * - `migrationDir` argument from Payload config\n * - `src/migrations`\n * - `dist/migrations`\n * - `migrations`\n *\n * Defaults to `src/migrations`\n *\n * @param migrationDir\n * @returns\n */\nfunction findMigrationDir(migrationDir?: string): string {\n const cwd = process.cwd()\n const srcDir = path.resolve(cwd, 'src/migrations')\n const distDir = path.resolve(cwd, 'dist/migrations')\n const relativeMigrations = path.resolve(cwd, 'migrations')\n\n // Use arg if provided\n if (migrationDir) {\n return migrationDir\n }\n\n // Check other common locations\n if (fs.existsSync(srcDir)) {\n return srcDir\n }\n\n if (fs.existsSync(distDir)) {\n return distDir\n }\n\n if (fs.existsSync(relativeMigrations)) {\n return relativeMigrations\n }\n\n return srcDir\n}\n"],"names":["fs","mongoose","path","createDatabaseAdapter","defaultBeginTransaction","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","allowAdditionalKeys","allowIDOnCreate","autoPluralization","collectionsSchemaOptions","connectOptions","disableFallbackSort","disableIndexHints","ensureIndexes","migrationDir","migrationDirArg","mongoMemoryServer","prodMigrations","transactionOptions","url","useAlternativeDropDatabase","useBigIntForNumberIDs","useJoinAggregations","usePipelineInSortLookup","adapter","payload","findMigrationDir","set","name","collections","connection","undefined","globals","sessions","versions","defaultIDType","packageName","compatabilityOptions","cwd","process","srcDir","resolve","distDir","relativeMigrations","existsSync"],"mappings":"AAuBA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,cAAc,WAAU;AAC/B,OAAOC,UAAU,OAAM;AACvB,SAASC,qBAAqB,EAAEC,uBAAuB,QAAQ,UAAS;AAIxE,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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C;YACAsD,eAAe;YACfrD;YACAC;YACAC;YACAC;YACA0B;YACAzB;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAC;YACAqB;YACAsB,aAAa;YACbX;YACAR;YACAvB;YACAG;YACAC;YACAC;YACAG;YACAC;YACAC;YACAgB;YACAC;YACAC;YACAC;QACF;IACF;IAEA,OAAO;QACLK,MAAM;QACNrB;QACA4B,eAAe;QACf3C,MAAMgC;IACR;AACF;AAEA,SAASa,oBAAoB,QAAQ,sCAAqC;AAE1E;;;;;;;;;;;;;CAaC,GACD,SAASX,iBAAiBZ,YAAqB;IAC7C,MAAMwB,MAAMC,QAAQD,GAAG;IACvB,MAAME,SAAStE,KAAKuE,OAAO,CAACH,KAAK;IACjC,MAAMI,UAAUxE,KAAKuE,OAAO,CAACH,KAAK;IAClC,MAAMK,qBAAqBzE,KAAKuE,OAAO,CAACH,KAAK;IAE7C,sBAAsB;IACtB,IAAIxB,cAAc;QAChB,OAAOA;IACT;IAEA,+BAA+B;IAC/B,IAAI9C,GAAG4E,UAAU,CAACJ,SAAS;QACzB,OAAOA;IACT;IAEA,IAAIxE,GAAG4E,UAAU,CAACF,UAAU;QAC1B,OAAOA;IACT;IAEA,IAAI1E,GAAG4E,UAAU,CAACD,qBAAqB;QACrC,OAAOA;IACT;IAEA,OAAOH;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"buildSchema.d.ts","sourceRoot":"","sources":["../../src/models/buildSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,MAAM,EAAE,aAAa,EAAqB,MAAM,UAAU,CAAA;AAGtF,OAAO,EAQL,KAAK,KAAK,EAMV,KAAK,OAAO,EAMZ,KAAK,sBAAsB,EAQ5B,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,OAAO,CAAC,EAAE,aAAa,CAAA;CACxB,CAAA;AAkFD,eAAO,MAAM,WAAW,SAAU;IAChC,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,eAAe,CAAC,EAAE,sBAAsB,EAAE,CAAA;IAC1C,YAAY,EAAE,KAAK,EAAE,CAAA;IACrB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,OAAO,EAAE,OAAO,CAAA;CACjB,KAAG,MAwDH,CAAA"}
1
+ {"version":3,"file":"buildSchema.d.ts","sourceRoot":"","sources":["../../src/models/buildSchema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,MAAM,EAAE,aAAa,EAAqB,MAAM,UAAU,CAAA;AAGtF,OAAO,EAQL,KAAK,KAAK,EAMV,KAAK,OAAO,EAMZ,KAAK,sBAAsB,EAQ5B,MAAM,SAAS,CAAA;AAShB,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,CAAC,EAAE,OAAO,CAAA;IACtB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,OAAO,CAAC,EAAE,aAAa,CAAA;CACxB,CAAA;AAkFD,eAAO,MAAM,WAAW,SAAU;IAChC,kBAAkB,EAAE,kBAAkB,CAAA;IACtC,eAAe,CAAC,EAAE,sBAAsB,EAAE,CAAA;IAC1C,YAAY,EAAE,KAAK,EAAE,CAAA;IACrB,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,OAAO,EAAE,OAAO,CAAA;CACjB,KAAG,MA6DH,CAAA"}
@@ -49,7 +49,7 @@ export const buildSchema = (args)=>{
49
49
  const idField = schemaFields.find((field)=>fieldAffectsData(field) && field.name === 'id');
50
50
  if (idField) {
51
51
  fields = {
52
- _id: idField.type === 'number' ? Number : String
52
+ _id: idField.type === 'number' ? payload.db.useBigIntForNumberIDs ? mongoose.Schema.Types.BigInt : Number : String
53
53
  };
54
54
  schemaFields = schemaFields.filter((field)=>!(fieldAffectsData(field) && field.name === 'id'));
55
55
  }
@@ -711,7 +711,11 @@ const getRelationshipValueType = (field, payload)=>{
711
711
  return mongoose.Schema.Types.ObjectId;
712
712
  }
713
713
  if (customIDType === 'number') {
714
- return mongoose.Schema.Types.Number;
714
+ if (payload.db.useBigIntForNumberIDs) {
715
+ return mongoose.Schema.Types.BigInt;
716
+ } else {
717
+ return mongoose.Schema.Types.Number;
718
+ }
715
719
  }
716
720
  return mongoose.Schema.Types.String;
717
721
  }