@payloadcms/db-mongodb 4.0.0-internal.cea8867 → 4.0.0-internal.d21c039
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/connect.d.ts.map +1 -1
- package/dist/connect.js +8 -2
- package/dist/connect.js.map +1 -1
- package/dist/create.d.ts.map +1 -1
- package/dist/create.js +2 -1
- package/dist/create.js.map +1 -1
- package/dist/createGlobalVersion.js +1 -1
- package/dist/createGlobalVersion.js.map +1 -1
- package/dist/createMigration.d.ts.map +1 -1
- package/dist/createMigration.js +9 -2
- package/dist/createMigration.js.map +1 -1
- package/dist/createVersion.js +1 -1
- package/dist/createVersion.js.map +1 -1
- package/dist/find.js +1 -1
- package/dist/find.js.map +1 -1
- package/dist/findDistinct.d.ts.map +1 -1
- package/dist/findDistinct.js +52 -8
- package/dist/findDistinct.js.map +1 -1
- package/dist/findOne.js +1 -1
- package/dist/findOne.js.map +1 -1
- package/dist/migrateFresh.d.ts +4 -2
- package/dist/migrateFresh.d.ts.map +1 -1
- package/dist/migrateFresh.js +20 -6
- package/dist/migrateFresh.js.map +1 -1
- package/dist/predefinedMigrations/migrateRelationshipsV2_V3.d.ts.map +1 -1
- package/dist/predefinedMigrations/migrateRelationshipsV2_V3.js +4 -4
- package/dist/predefinedMigrations/migrateRelationshipsV2_V3.js.map +1 -1
- package/dist/queries/buildSearchParams.d.ts.map +1 -1
- package/dist/queries/buildSearchParams.js +189 -6
- package/dist/queries/buildSearchParams.js.map +1 -1
- package/dist/queries/parseParams.js.map +1 -1
- package/dist/queryDrafts.js +1 -1
- package/dist/queryDrafts.js.map +1 -1
- package/dist/updateJobs.d.ts.map +1 -1
- package/dist/updateJobs.js +70 -13
- package/dist/updateJobs.js.map +1 -1
- package/dist/utilities/buildJoinAggregation.d.ts +1 -1
- package/dist/utilities/buildJoinAggregation.d.ts.map +1 -1
- package/dist/utilities/buildJoinAggregation.js +2 -2
- package/dist/utilities/buildJoinAggregation.js.map +1 -1
- package/dist/utilities/transform.d.ts.map +1 -1
- package/dist/utilities/transform.js +15 -0
- package/dist/utilities/transform.js.map +1 -1
- package/package.json +5 -5
- package/dist/queries/buildSortParam.spec.js +0 -123
- package/dist/queries/buildSortParam.spec.js.map +0 -1
- package/dist/queries/getLocalizedSortProperty.spec.js +0 -215
- package/dist/queries/getLocalizedSortProperty.spec.js.map +0 -1
- package/dist/utilities/transform.spec.js +0 -479
- package/dist/utilities/transform.spec.js.map +0 -1
package/dist/connect.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,SAAS,CAAA;AAOjD,eAAO,MAAM,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,SAAS,CAAA;AAOjD,eAAO,MAAM,OAAO,EAAE,OAkHrB,CAAA"}
|
package/dist/connect.js
CHANGED
|
@@ -64,8 +64,14 @@ export const connect = async function connect(options = {
|
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
if (this.ensureIndexes) {
|
|
67
|
-
await Promise.all(
|
|
68
|
-
|
|
67
|
+
await Promise.all([
|
|
68
|
+
...this.payload.config.collections.flatMap((collection)=>[
|
|
69
|
+
this.collections[collection.slug],
|
|
70
|
+
this.versions[collection.slug]
|
|
71
|
+
]),
|
|
72
|
+
...this.payload.config.globals.map((global)=>this.versions[global.slug])
|
|
73
|
+
].map(async (model)=>{
|
|
74
|
+
await model?.ensureIndexes();
|
|
69
75
|
}));
|
|
70
76
|
}
|
|
71
77
|
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
|
package/dist/connect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect, Migration } 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: ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n if (!this.connection) {\n this.connection = await mongoose.createConnection(urlToConnect, connectionOptions).asPromise()\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n }\n\n await this.connection.openUri(urlToConnect, connectionOptions)\n\n if (this.afterOpenConnection) {\n await this.afterOpenConnection(this)\n }\n\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 if (!this.connection.getClient().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 this.connection.dropDatabase()\n\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n this.payload.config.collections.
|
|
1
|
+
{"version":3,"sources":["../src/connect.ts"],"sourcesContent":["import type { ConnectOptions } from 'mongoose'\nimport type { Connect, Migration } 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: ConnectOptions = {\n autoIndex: true,\n ...this.connectOptions,\n }\n\n if (hotReload) {\n connectionOptions.autoIndex = false\n }\n\n try {\n if (!this.connection) {\n this.connection = await mongoose.createConnection(urlToConnect, connectionOptions).asPromise()\n if (this.afterCreateConnection) {\n await this.afterCreateConnection(this)\n }\n }\n\n await this.connection.openUri(urlToConnect, connectionOptions)\n\n if (this.afterOpenConnection) {\n await this.afterOpenConnection(this)\n }\n\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 if (!this.connection.getClient().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 this.connection.dropDatabase()\n\n this.payload.logger.info('---- DROPPED DATABASE ----')\n }\n }\n\n if (this.ensureIndexes) {\n await Promise.all(\n [\n ...this.payload.config.collections.flatMap((collection) => [\n this.collections[collection.slug],\n this.versions[collection.slug],\n ]),\n ...this.payload.config.globals.map((global) => this.versions[global.slug]),\n ].map(async (model) => {\n await model?.ensureIndexes()\n }),\n )\n }\n\n if (process.env.NODE_ENV === 'production' && this.prodMigrations) {\n await this.migrate({ migrations: this.prodMigrations as unknown as Migration[] })\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 throw new Error(`Error: cannot connect to MongoDB: ${msg}`)\n }\n}\n"],"names":["mongoose","defaultBeginTransaction","connect","options","hotReload","url","Error","urlToConnect","connectionOptions","autoIndex","connectOptions","connection","createConnection","asPromise","afterCreateConnection","openUri","afterOpenConnection","useAlternativeDropDatabase","db","dropDatabase","existingCollections","listCollections","toArray","Promise","all","map","collectionInfo","collection","name","deleteMany","mongoMemoryServer","payload","logger","info","resolve","setTimeout","getClient","replicaSet","transactionOptions","beginTransaction","process","env","PAYLOAD_DROP_DATABASE","ensureIndexes","config","collections","flatMap","slug","versions","globals","global","model","NODE_ENV","prodMigrations","migrate","migrations","err","msg","message","error"],"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,CAAC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KAAK,UAAU;YACzFD,MAAM,GAAGA,IAAI,UAAU,EAAED,IAAIE,OAAO,EAAE;QACxC;QAEA,IAAI,CAAC3B,OAAO,CAACC,MAAM,CAAC2B,KAAK,CAAC;YACxBH;YACAC;QACF;QACA,MAAM,IAAInD,MAAM,CAAC,kCAAkC,EAAEmD,KAAK;IAC5D;AACF,EAAC"}
|
package/dist/create.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAWrC,eAAO,MAAM,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"create.d.ts","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAWrC,eAAO,MAAM,MAAM,EAAE,MAgEpB,CAAA"}
|
package/dist/create.js
CHANGED
|
@@ -21,7 +21,8 @@ export const create = async function create({ collection: collectionSlug, custom
|
|
|
21
21
|
if (customIDType) {
|
|
22
22
|
data._id = data.id;
|
|
23
23
|
} else if (customID) {
|
|
24
|
-
|
|
24
|
+
// Mongoose 9 no longer treats numbers as valid ObjectIDs, so only strings are worth casting
|
|
25
|
+
if (typeof customID === 'string' && Types.ObjectId.isValid(customID)) {
|
|
25
26
|
data._id = new Types.ObjectId(customID);
|
|
26
27
|
} else {
|
|
27
28
|
data._id = customID;
|
package/dist/create.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/create.ts"],"sourcesContent":["import type { Create } from 'payload'\n\nimport { type CreateOptions, Types } from 'mongoose'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { handleError } from './utilities/handleError.js'\nimport { transform } from './utilities/transform.js'\n\nexport const create: Create = async function create(\n this: MongooseAdapter,\n { collection: collectionSlug, customID, data, req, returning },\n) {\n const { collectionConfig, customIDType, Model } = getCollection({ adapter: this, collectionSlug })\n\n let doc\n\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n transform({\n adapter: this,\n data,\n fields: collectionConfig.fields,\n operation: 'write',\n })\n\n if (customIDType) {\n data._id = data.id\n } else if (customID) {\n if (Types.ObjectId.isValid(customID)) {\n data._id = new Types.ObjectId(customID)\n } else {\n data._id = customID\n }\n } else if (this.allowIDOnCreate && data.id) {\n try {\n data._id = new Types.ObjectId(data.id as string)\n } catch (error) {\n this.payload.logger.error(\n `It appears you passed ID to create operation data but it cannot be sanitized to ObjectID, value - ${JSON.stringify(data.id)}`,\n )\n throw error\n }\n }\n\n const options: CreateOptions = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n try {\n ;[doc] = await Model.create([data], options)\n } catch (error) {\n handleError({ collection: collectionSlug, error, req })\n }\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["Types","getCollection","getSession","handleError","transform","create","collection","collectionSlug","customID","data","req","returning","collectionConfig","customIDType","Model","adapter","doc","createdAt","Date","toISOString","fields","operation","_id","id","ObjectId","isValid","allowIDOnCreate","error","payload","logger","JSON","stringify","options","session","timestamps","toObject"],"mappings":"AAEA,SAA6BA,KAAK,QAAQ,WAAU;AAIpD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,WAAW,QAAQ,6BAA4B;AACxD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,SAAiB,eAAeA,OAE3C,EAAEC,YAAYC,cAAc,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,GAAG,EAAEC,SAAS,EAAE;IAE9D,MAAM,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,KAAK,EAAE,GAAGb,cAAc;QAAEc,SAAS,IAAI;QAAER;IAAe;IAEhG,IAAIS;IAEJ,IAAI,CAACP,KAAKQ,SAAS,EAAE;QACnBR,KAAKQ,SAAS,GAAG,IAAIC,OAAOC,WAAW;IACzC;IAEAf,UAAU;QACRW,SAAS,IAAI;QACbN;QACAW,QAAQR,iBAAiBQ,MAAM;QAC/BC,WAAW;IACb;IAEA,IAAIR,cAAc;QAChBJ,KAAKa,GAAG,GAAGb,KAAKc,EAAE;IACpB,OAAO,IAAIf,UAAU;QACnB,
|
|
1
|
+
{"version":3,"sources":["../src/create.ts"],"sourcesContent":["import type { Create } from 'payload'\n\nimport { type CreateOptions, Types } from 'mongoose'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { handleError } from './utilities/handleError.js'\nimport { transform } from './utilities/transform.js'\n\nexport const create: Create = async function create(\n this: MongooseAdapter,\n { collection: collectionSlug, customID, data, req, returning },\n) {\n const { collectionConfig, customIDType, Model } = getCollection({ adapter: this, collectionSlug })\n\n let doc\n\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n transform({\n adapter: this,\n data,\n fields: collectionConfig.fields,\n operation: 'write',\n })\n\n if (customIDType) {\n data._id = data.id\n } else if (customID) {\n // Mongoose 9 no longer treats numbers as valid ObjectIDs, so only strings are worth casting\n if (typeof customID === 'string' && Types.ObjectId.isValid(customID)) {\n data._id = new Types.ObjectId(customID)\n } else {\n data._id = customID\n }\n } else if (this.allowIDOnCreate && data.id) {\n try {\n data._id = new Types.ObjectId(data.id as string)\n } catch (error) {\n this.payload.logger.error(\n `It appears you passed ID to create operation data but it cannot be sanitized to ObjectID, value - ${JSON.stringify(data.id)}`,\n )\n throw error\n }\n }\n\n const options: CreateOptions = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n try {\n ;[doc] = await Model.create([data], options)\n } catch (error) {\n handleError({ collection: collectionSlug, error, req })\n }\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields: collectionConfig.fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["Types","getCollection","getSession","handleError","transform","create","collection","collectionSlug","customID","data","req","returning","collectionConfig","customIDType","Model","adapter","doc","createdAt","Date","toISOString","fields","operation","_id","id","ObjectId","isValid","allowIDOnCreate","error","payload","logger","JSON","stringify","options","session","timestamps","toObject"],"mappings":"AAEA,SAA6BA,KAAK,QAAQ,WAAU;AAIpD,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,WAAW,QAAQ,6BAA4B;AACxD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,SAAiB,eAAeA,OAE3C,EAAEC,YAAYC,cAAc,EAAEC,QAAQ,EAAEC,IAAI,EAAEC,GAAG,EAAEC,SAAS,EAAE;IAE9D,MAAM,EAAEC,gBAAgB,EAAEC,YAAY,EAAEC,KAAK,EAAE,GAAGb,cAAc;QAAEc,SAAS,IAAI;QAAER;IAAe;IAEhG,IAAIS;IAEJ,IAAI,CAACP,KAAKQ,SAAS,EAAE;QACnBR,KAAKQ,SAAS,GAAG,IAAIC,OAAOC,WAAW;IACzC;IAEAf,UAAU;QACRW,SAAS,IAAI;QACbN;QACAW,QAAQR,iBAAiBQ,MAAM;QAC/BC,WAAW;IACb;IAEA,IAAIR,cAAc;QAChBJ,KAAKa,GAAG,GAAGb,KAAKc,EAAE;IACpB,OAAO,IAAIf,UAAU;QACnB,4FAA4F;QAC5F,IAAI,OAAOA,aAAa,YAAYR,MAAMwB,QAAQ,CAACC,OAAO,CAACjB,WAAW;YACpEC,KAAKa,GAAG,GAAG,IAAItB,MAAMwB,QAAQ,CAAChB;QAChC,OAAO;YACLC,KAAKa,GAAG,GAAGd;QACb;IACF,OAAO,IAAI,IAAI,CAACkB,eAAe,IAAIjB,KAAKc,EAAE,EAAE;QAC1C,IAAI;YACFd,KAAKa,GAAG,GAAG,IAAItB,MAAMwB,QAAQ,CAACf,KAAKc,EAAE;QACvC,EAAE,OAAOI,OAAO;YACd,IAAI,CAACC,OAAO,CAACC,MAAM,CAACF,KAAK,CACvB,CAAC,kGAAkG,EAAEG,KAAKC,SAAS,CAACtB,KAAKc,EAAE,GAAG;YAEhI,MAAMI;QACR;IACF;IAEA,MAAMK,UAAyB;QAC7BC,SAAS,MAAM/B,WAAW,IAAI,EAAEQ;QAChC,uDAAuD;QACvDwB,YAAY;IACd;IAEA,IAAI;;QACD,CAAClB,IAAI,GAAG,MAAMF,MAAMT,MAAM,CAAC;YAACI;SAAK,EAAEuB;IACtC,EAAE,OAAOL,OAAO;QACdxB,YAAY;YAAEG,YAAYC;YAAgBoB;YAAOjB;QAAI;IACvD;IACA,IAAIC,cAAc,OAAO;QACvB,OAAO;IACT;IAEAK,MAAMA,IAAImB,QAAQ;IAElB/B,UAAU;QACRW,SAAS,IAAI;QACbN,MAAMO;QACNI,QAAQR,iBAAiBQ,MAAM;QAC/BC,WAAW;IACb;IAEA,OAAOL;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import { buildVersionGlobalFields, type CreateGlobalVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(\n this: MongooseAdapter,\n {\n autosave,\n createdAt,\n globalSlug,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { globalConfig, Model } = getGlobal({ adapter: this, globalSlug, versions: true })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionGlobalFields(this.payload.config, globalConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options
|
|
1
|
+
{"version":3,"sources":["../src/createGlobalVersion.ts"],"sourcesContent":["import { buildVersionGlobalFields, type CreateGlobalVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getGlobal } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(\n this: MongooseAdapter,\n {\n autosave,\n createdAt,\n globalSlug,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { globalConfig, Model } = getGlobal({ adapter: this, globalSlug, versions: true })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionGlobalFields(this.payload.config, globalConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options)\n\n await Model.updateMany(\n {\n $and: [\n {\n _id: {\n $ne: doc._id,\n },\n },\n {\n latest: {\n $eq: true,\n },\n },\n ],\n },\n { $unset: { latest: 1 } },\n options,\n )\n\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["buildVersionGlobalFields","getGlobal","getSession","transform","createGlobalVersion","autosave","createdAt","globalSlug","publishedLocale","req","returning","snapshot","updatedAt","versionData","globalConfig","Model","adapter","versions","data","latest","version","Date","toISOString","fields","payload","config","operation","options","session","timestamps","doc","create","updateMany","$and","_id","$ne","$eq","$unset","toObject"],"mappings":"AAAA,SAASA,wBAAwB,QAAkC,UAAS;AAI5E,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,sBAA2C,eAAeA,oBAErE,EACEC,QAAQ,EACRC,SAAS,EACTC,UAAU,EACVC,eAAe,EACfC,GAAG,EACHC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,WAAW,EACZ;IAED,MAAM,EAAEC,YAAY,EAAEC,KAAK,EAAE,GAAGd,UAAU;QAAEe,SAAS,IAAI;QAAET;QAAYU,UAAU;IAAK;IAEtF,MAAMC,OAAO;QACXb;QACAC;QACAa,QAAQ;QACRX;QACAG;QACAC;QACAQ,SAASP;IACX;IACA,IAAI,CAACK,KAAKZ,SAAS,EAAE;QACnBY,KAAKZ,SAAS,GAAG,IAAIe,OAAOC,WAAW;IACzC;IAEA,MAAMC,SAASvB,yBAAyB,IAAI,CAACwB,OAAO,CAACC,MAAM,EAAEX;IAE7DX,UAAU;QACRa,SAAS,IAAI;QACbE;QACAK;QACAG,WAAW;IACb;IAEA,MAAMC,UAAU;QACdC,SAAS,MAAM1B,WAAW,IAAI,EAAEO;QAChC,uDAAuD;QACvDoB,YAAY;IACd;IAEA,IAAI,CAACC,IAAI,GAAG,MAAMf,MAAMgB,MAAM,CAAC;QAACb;KAAK,EAAES;IAEvC,MAAMZ,MAAMiB,UAAU,CACpB;QACEC,MAAM;YACJ;gBACEC,KAAK;oBACHC,KAAKL,IAAII,GAAG;gBACd;YACF;YACA;gBACEf,QAAQ;oBACNiB,KAAK;gBACP;YACF;SACD;IACH,GACA;QAAEC,QAAQ;YAAElB,QAAQ;QAAE;IAAE,GACxBQ;IAGF,IAAIjB,cAAc,OAAO;QACvB,OAAO;IACT;IAEAoB,MAAMA,IAAIQ,QAAQ;IAElBnC,UAAU;QACRa,SAAS,IAAI;QACbE,MAAMY;QACNP;QACAG,WAAW;IACb;IAEA,OAAOI;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;AAqBrE,eAAO,MAAM,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"createMigration.d.ts","sourceRoot":"","sources":["../src/createMigration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAyB,MAAM,SAAS,CAAA;AAqBrE,eAAO,MAAM,eAAe,EAAE,eA4C7B,CAAA"}
|
package/dist/createMigration.js
CHANGED
|
@@ -36,15 +36,22 @@ export const createMigration = async function createMigration({ file, migrationN
|
|
|
36
36
|
const formattedName = migrationName?.replace(/\W/g, '_');
|
|
37
37
|
const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`;
|
|
38
38
|
const filePath = `${dir}/${fileName}`;
|
|
39
|
-
if (
|
|
40
|
-
|
|
39
|
+
if (skipEmpty) {
|
|
40
|
+
return {
|
|
41
|
+
created: false
|
|
42
|
+
};
|
|
41
43
|
}
|
|
44
|
+
fs.writeFileSync(filePath, migrationFileContent);
|
|
42
45
|
writeMigrationIndex({
|
|
43
46
|
migrationsDir: payload.db.migrationDir
|
|
44
47
|
});
|
|
45
48
|
payload.logger.info({
|
|
46
49
|
msg: `Migration created at ${filePath}`
|
|
47
50
|
});
|
|
51
|
+
return {
|
|
52
|
+
created: true,
|
|
53
|
+
path: filePath
|
|
54
|
+
};
|
|
48
55
|
};
|
|
49
56
|
|
|
50
57
|
//# sourceMappingURL=createMigration.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateDownArgs,\n MigrateUpArgs,\n} from '@payloadcms/db-mongodb'\n${imports ?? ''}\nexport async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n skipEmpty,\n}) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n const migrationFileContent = migrationTemplate(predefinedMigration)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n\n const formattedDate = yyymmdd!.replace(/\\D/g, '')\n const formattedTime = hhmmss!.split('.')[0]!.replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const formattedName = migrationName?.replace(/\\W/g, '_')\n const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`\n const filePath = `${dir}/${fileName}`\n\n if (
|
|
1
|
+
{"version":3,"sources":["../src/createMigration.ts"],"sourcesContent":["import type { CreateMigration, MigrationTemplateArgs } from 'payload'\n\nimport fs from 'fs'\nimport path from 'path'\nimport { getPredefinedMigration, writeMigrationIndex } from 'payload'\nimport { fileURLToPath } from 'url'\n\nconst migrationTemplate = ({ downSQL, imports, upSQL }: MigrationTemplateArgs): string => `import {\n MigrateDownArgs,\n MigrateUpArgs,\n} from '@payloadcms/db-mongodb'\n${imports ?? ''}\nexport async function up({ payload, req, session }: MigrateUpArgs): Promise<void> {\n${upSQL ?? ` // Migration code`}\n}\n\nexport async function down({ payload, req, session }: MigrateDownArgs): Promise<void> {\n${downSQL ?? ` // Migration code`}\n}\n`\n\nexport const createMigration: CreateMigration = async function createMigration({\n file,\n migrationName,\n payload,\n skipEmpty,\n}) {\n const filename = fileURLToPath(import.meta.url)\n const dirname = path.dirname(filename)\n\n const dir = payload.db.migrationDir\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir)\n }\n const predefinedMigration = await getPredefinedMigration({\n dirname,\n file,\n migrationName,\n payload,\n })\n\n const migrationFileContent = migrationTemplate(predefinedMigration)\n\n const [yyymmdd, hhmmss] = new Date().toISOString().split('T')\n\n const formattedDate = yyymmdd!.replace(/\\D/g, '')\n const formattedTime = hhmmss!.split('.')[0]!.replace(/\\D/g, '')\n\n const timestamp = `${formattedDate}_${formattedTime}`\n\n const formattedName = migrationName?.replace(/\\W/g, '_')\n const fileName = migrationName ? `${timestamp}_${formattedName}.ts` : `${timestamp}_migration.ts`\n const filePath = `${dir}/${fileName}`\n\n if (skipEmpty) {\n return { created: false }\n }\n\n fs.writeFileSync(filePath, migrationFileContent)\n\n writeMigrationIndex({ migrationsDir: payload.db.migrationDir })\n\n payload.logger.info({ msg: `Migration created at ${filePath}` })\n\n return { created: true, path: filePath }\n}\n"],"names":["fs","path","getPredefinedMigration","writeMigrationIndex","fileURLToPath","migrationTemplate","downSQL","imports","upSQL","createMigration","file","migrationName","payload","skipEmpty","filename","url","dirname","dir","db","migrationDir","existsSync","mkdirSync","predefinedMigration","migrationFileContent","yyymmdd","hhmmss","Date","toISOString","split","formattedDate","replace","formattedTime","timestamp","formattedName","fileName","filePath","created","writeFileSync","migrationsDir","logger","info","msg"],"mappings":"AAEA,OAAOA,QAAQ,KAAI;AACnB,OAAOC,UAAU,OAAM;AACvB,SAASC,sBAAsB,EAAEC,mBAAmB,QAAQ,UAAS;AACrE,SAASC,aAAa,QAAQ,MAAK;AAEnC,MAAMC,oBAAoB,CAAC,EAAEC,OAAO,EAAEC,OAAO,EAAEC,KAAK,EAAy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;QAAEC,KAAK,CAAC,qBAAqB,EAAEN,UAAU;IAAC;IAE9D,OAAO;QAAEC,SAAS;QAAMnC,MAAMkC;IAAS;AACzC,EAAC"}
|
package/dist/createVersion.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import { buildVersionCollectionFields, type CreateVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createVersion: CreateVersion = async function createVersion(\n this: MongooseAdapter,\n {\n autosave,\n collectionSlug,\n createdAt,\n parent,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug,\n versions: true,\n })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n parent,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionCollectionFields(this.payload.config, collectionConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options
|
|
1
|
+
{"version":3,"sources":["../src/createVersion.ts"],"sourcesContent":["import { buildVersionCollectionFields, type CreateVersion } from 'payload'\n\nimport type { MongooseAdapter } from './index.js'\n\nimport { getCollection } from './utilities/getEntity.js'\nimport { getSession } from './utilities/getSession.js'\nimport { transform } from './utilities/transform.js'\n\nexport const createVersion: CreateVersion = async function createVersion(\n this: MongooseAdapter,\n {\n autosave,\n collectionSlug,\n createdAt,\n parent,\n publishedLocale,\n req,\n returning,\n snapshot,\n updatedAt,\n versionData,\n },\n) {\n const { collectionConfig, Model } = getCollection({\n adapter: this,\n collectionSlug,\n versions: true,\n })\n\n const data = {\n autosave,\n createdAt,\n latest: true,\n parent,\n publishedLocale,\n snapshot,\n updatedAt,\n version: versionData,\n }\n if (!data.createdAt) {\n data.createdAt = new Date().toISOString()\n }\n\n const fields = buildVersionCollectionFields(this.payload.config, collectionConfig)\n\n transform({\n adapter: this,\n data,\n fields,\n operation: 'write',\n })\n\n const options = {\n session: await getSession(this, req),\n // Timestamps are manually added by the write transform\n timestamps: false,\n }\n\n let [doc] = await Model.create([data], options)\n\n const parentQuery = {\n $or: [\n {\n parent: {\n $eq: data.parent,\n },\n },\n ],\n }\n\n await Model.updateMany(\n {\n $and: [\n {\n _id: {\n $ne: doc._id,\n },\n },\n parentQuery,\n {\n latest: {\n $eq: true,\n },\n },\n {\n updatedAt: {\n $lt: new Date(doc.updatedAt),\n },\n },\n ],\n },\n { $unset: { latest: 1 } },\n options,\n )\n\n if (returning === false) {\n return null\n }\n\n doc = doc.toObject()\n\n transform({\n adapter: this,\n data: doc,\n fields,\n operation: 'read',\n })\n\n return doc\n}\n"],"names":["buildVersionCollectionFields","getCollection","getSession","transform","createVersion","autosave","collectionSlug","createdAt","parent","publishedLocale","req","returning","snapshot","updatedAt","versionData","collectionConfig","Model","adapter","versions","data","latest","version","Date","toISOString","fields","payload","config","operation","options","session","timestamps","doc","create","parentQuery","$or","$eq","updateMany","$and","_id","$ne","$lt","$unset","toObject"],"mappings":"AAAA,SAASA,4BAA4B,QAA4B,UAAS;AAI1E,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AACtD,SAASC,SAAS,QAAQ,2BAA0B;AAEpD,OAAO,MAAMC,gBAA+B,eAAeA,cAEzD,EACEC,QAAQ,EACRC,cAAc,EACdC,SAAS,EACTC,MAAM,EACNC,eAAe,EACfC,GAAG,EACHC,SAAS,EACTC,QAAQ,EACRC,SAAS,EACTC,WAAW,EACZ;IAED,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGf,cAAc;QAChDgB,SAAS,IAAI;QACbX;QACAY,UAAU;IACZ;IAEA,MAAMC,OAAO;QACXd;QACAE;QACAa,QAAQ;QACRZ;QACAC;QACAG;QACAC;QACAQ,SAASP;IACX;IACA,IAAI,CAACK,KAAKZ,SAAS,EAAE;QACnBY,KAAKZ,SAAS,GAAG,IAAIe,OAAOC,WAAW;IACzC;IAEA,MAAMC,SAASxB,6BAA6B,IAAI,CAACyB,OAAO,CAACC,MAAM,EAAEX;IAEjEZ,UAAU;QACRc,SAAS,IAAI;QACbE;QACAK;QACAG,WAAW;IACb;IAEA,MAAMC,UAAU;QACdC,SAAS,MAAM3B,WAAW,IAAI,EAAEQ;QAChC,uDAAuD;QACvDoB,YAAY;IACd;IAEA,IAAI,CAACC,IAAI,GAAG,MAAMf,MAAMgB,MAAM,CAAC;QAACb;KAAK,EAAES;IAEvC,MAAMK,cAAc;QAClBC,KAAK;YACH;gBACE1B,QAAQ;oBACN2B,KAAKhB,KAAKX,MAAM;gBAClB;YACF;SACD;IACH;IAEA,MAAMQ,MAAMoB,UAAU,CACpB;QACEC,MAAM;YACJ;gBACEC,KAAK;oBACHC,KAAKR,IAAIO,GAAG;gBACd;YACF;YACAL;YACA;gBACEb,QAAQ;oBACNe,KAAK;gBACP;YACF;YACA;gBACEtB,WAAW;oBACT2B,KAAK,IAAIlB,KAAKS,IAAIlB,SAAS;gBAC7B;YACF;SACD;IACH,GACA;QAAE4B,QAAQ;YAAErB,QAAQ;QAAE;IAAE,GACxBQ;IAGF,IAAIjB,cAAc,OAAO;QACvB,OAAO;IACT;IAEAoB,MAAMA,IAAIW,QAAQ;IAElBvC,UAAU;QACRc,SAAS,IAAI;QACbE,MAAMY;QACNP;QACAG,WAAW;IACb;IAEA,OAAOI;AACT,EAAC"}
|
package/dist/find.js
CHANGED
|
@@ -114,7 +114,7 @@ export const find = async function find({ collection: collectionSlug, draftsEnab
|
|
|
114
114
|
projection: paginationOptions.projection,
|
|
115
115
|
query
|
|
116
116
|
});
|
|
117
|
-
if (aggregate || sortAggregation.length > 0) {
|
|
117
|
+
if (aggregate.length > 0 || sortAggregation.length > 0) {
|
|
118
118
|
result = await aggregatePaginate({
|
|
119
119
|
adapter: this,
|
|
120
120
|
collation: paginationOptions.collation,
|
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 localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\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 collation: paginationOptions.collation,\n hint: { _id: 1 },\n session,\n }),\n )\n }\n } else if (!useEstimatedCount && this.collation) {\n // Workaround for mongoose-paginate-v2 bug: chaining .collation() on countDocuments breaks\n // session context in transactions (mongoose 8.x). Provide custom count function that passes\n // collation as an option instead. See: https://github.com/aravindnc/mongoose-paginate-v2/pull/240\n // TODO: Remove this workaround once mongoose-paginate-v2 is updated with the fix.\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\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","localizationConfig","localization","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,8B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;IACF;IAEA,IAAI2C;IAEJ,MAAMC,YAAY,MAAM1D,qBAAqB;QAC3CuB,SAAS,IAAI;QACbhB,YAAYC;QACZa;QACAZ;QACAC;QACAE;QACAG,YAAY2B,kBAAkB3B,UAAU;QACxCuB;IACF;IAEA,IAAIoB,aAAa3B,gBAAgBU,MAAM,GAAG,GAAG;QAC3CgB,SAAS,MAAM1D,kBAAkB;YAC/BwB,SAAS,IAAI;YACbuB,WAAWJ,kBAAkBI,SAAS;YACtCa,iBAAiBD;YACjB/C,OAAO+B,kBAAkB/B,KAAK;YAC9BW;YACAT,MAAM6B,kBAAkB7B,IAAI;YAC5BC,YAAY4B,kBAAkB5B,UAAU;YACxCC,YAAY2B,kBAAkB3B,UAAU;YACxCuB;YACAC,SAASG,kBAAkBG,OAAO,EAAEN,WAAWqB;YAC/C1C,MAAMwB,kBAAkBxB,IAAI;YAC5Ba;YACAS,mBAAmBE,kBAAkBF,iBAAiB;QACxD;IACF,OAAO;QACLiB,SAAS,MAAMnC,MAAMuC,QAAQ,CAACvB,OAAOI;IACvC;IAEA,IAAI,CAAC,IAAI,CAACoB,mBAAmB,EAAE;QAC7B,MAAM1D,aAAa;YACjBmB,SAAS,IAAI;YACbf;YACAuD,MAAMN,OAAOM,IAAI;YACjBrD;YACAE;QACF;IACF;IAEAP,UAAU;QACRkB,SAAS,IAAI;QACbyC,MAAMP,OAAOM,IAAI;QACjB7B,QAAQb,iBAAiBa,MAAM;QAC/B+B,WAAW;IACb;IAEA,OAAOR;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 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 localizationConfig = this.payload.config.localization\n const defaultLocale =\n (typeof localizationConfig === 'object' && localizationConfig?.defaultLocale) || 'en'\n\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 collation: paginationOptions.collation,\n hint: { _id: 1 },\n session,\n }),\n )\n }\n } else if (!useEstimatedCount && this.collation) {\n // Workaround for mongoose-paginate-v2 bug: chaining .collation() on countDocuments breaks\n // session context in transactions (mongoose 8.x). Provide custom count function that passes\n // collation as an option instead. See: https://github.com/aravindnc/mongoose-paginate-v2/pull/240\n // TODO: Remove this workaround once mongoose-paginate-v2 is updated with the fix.\n paginationOptions.useCustomCountFn = () => {\n return Promise.resolve(\n Model.countDocuments(query, {\n collation: paginationOptions.collation,\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.length > 0 || 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","localizationConfig","localization","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,wBAAwBw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,YAAY2B,kBAAkB3B,UAAU;YACxCuB;YACAC,SAASG,kBAAkBG,OAAO,EAAEN,WAAWqB;YAC/C1C,MAAMwB,kBAAkBxB,IAAI;YAC5Ba;YACAS,mBAAmBE,kBAAkBF,iBAAiB;QACxD;IACF,OAAO;QACLiB,SAAS,MAAMnC,MAAMuC,QAAQ,CAACvB,OAAOI;IACvC;IAEA,IAAI,CAAC,IAAI,CAACoB,mBAAmB,EAAE;QAC7B,MAAM1D,aAAa;YACjBmB,SAAS,IAAI;YACbf;YACAuD,MAAMN,OAAOM,IAAI;YACjBrD;YACAE;QACF;IACF;IAEAP,UAAU;QACRkB,SAAS,IAAI;QACbyC,MAAMP,OAAOM,IAAI;QACjB7B,QAAQb,iBAAiBa,MAAM;QAC/B+B,WAAW;IACb;IAEA,OAAOR;AACT,EAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"findDistinct.d.ts","sourceRoot":"","sources":["../src/findDistinct.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,SAAS,CAAA;AA6C3D,eAAO,MAAM,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"findDistinct.d.ts","sourceRoot":"","sources":["../src/findDistinct.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAkB,MAAM,SAAS,CAAA;AA6C3D,eAAO,MAAM,YAAY,EAAE,YA4S1B,CAAA"}
|
package/dist/findDistinct.js
CHANGED
|
@@ -114,30 +114,74 @@ export const findDistinct = async function(args) {
|
|
|
114
114
|
sortProperty = sortWithoutRelationPrefix;
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
|
-
relationLookup =
|
|
117
|
+
relationLookup = [];
|
|
118
|
+
for (const { fieldPath, relationTo } of rels){
|
|
118
119
|
sortAggregation = sortAggregation.filter((each)=>{
|
|
119
120
|
if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {
|
|
120
121
|
return false;
|
|
121
122
|
}
|
|
122
123
|
return true;
|
|
123
124
|
});
|
|
124
|
-
const { Model: foreignModel } = getCollection({
|
|
125
|
+
const { collectionConfig: foreignCollectionConfig, Model: foreignModel } = getCollection({
|
|
125
126
|
adapter: this,
|
|
126
127
|
collectionSlug: relationTo
|
|
127
128
|
});
|
|
128
|
-
|
|
129
|
+
const relatedAccess = args.relatedAccess?.[fieldPath];
|
|
130
|
+
const relatedAccessQuery = relatedAccess ? await buildQuery({
|
|
131
|
+
adapter: this,
|
|
132
|
+
collectionSlug: relationTo,
|
|
133
|
+
fields: foreignCollectionConfig.flattenedFields,
|
|
134
|
+
locale: args.locale,
|
|
135
|
+
where: relatedAccess
|
|
136
|
+
}) : null;
|
|
137
|
+
relationLookup.push({
|
|
129
138
|
$lookup: {
|
|
130
139
|
as: fieldPath,
|
|
131
|
-
foreignField: '_id',
|
|
132
140
|
from: foreignModel.collection.name,
|
|
133
|
-
|
|
141
|
+
...relatedAccessQuery ? {
|
|
142
|
+
let: {
|
|
143
|
+
relatedIDs: `$${fieldPath}`
|
|
144
|
+
},
|
|
145
|
+
pipeline: [
|
|
146
|
+
{
|
|
147
|
+
$match: {
|
|
148
|
+
$and: [
|
|
149
|
+
{
|
|
150
|
+
$expr: {
|
|
151
|
+
$cond: {
|
|
152
|
+
else: {
|
|
153
|
+
$eq: [
|
|
154
|
+
'$_id',
|
|
155
|
+
'$$relatedIDs'
|
|
156
|
+
]
|
|
157
|
+
},
|
|
158
|
+
if: {
|
|
159
|
+
$isArray: '$$relatedIDs'
|
|
160
|
+
},
|
|
161
|
+
then: {
|
|
162
|
+
$in: [
|
|
163
|
+
'$_id',
|
|
164
|
+
'$$relatedIDs'
|
|
165
|
+
]
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
relatedAccessQuery
|
|
171
|
+
]
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
]
|
|
175
|
+
} : {
|
|
176
|
+
foreignField: '_id',
|
|
177
|
+
localField: fieldPath
|
|
178
|
+
}
|
|
134
179
|
}
|
|
135
180
|
});
|
|
136
|
-
|
|
181
|
+
relationLookup.push({
|
|
137
182
|
$unwind: `$${fieldPath}`
|
|
138
183
|
});
|
|
139
|
-
|
|
140
|
-
}, []);
|
|
184
|
+
}
|
|
141
185
|
}
|
|
142
186
|
let $unwind = '';
|
|
143
187
|
let $group = null;
|
package/dist/findDistinct.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/findDistinct.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { FindDistinct, FlattenedField } from 'payload'\n\nimport { 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\nconst sanitizeGroupID = (id: any) => {\n if (id && typeof id === 'object' && '_field' in id) {\n return id._field\n }\n\n return id\n}\n\nconst getSortAggregation = ({\n fieldPath,\n hasSortAggregationAndHasMany,\n sortDirection,\n sortProperty,\n}: {\n fieldPath: string\n hasSortAggregationAndHasMany: boolean\n sortDirection: -1 | 1\n sortProperty: string\n}): Record<string, -1 | 1> => {\n let resolvedSortProperty: string\n\n if (hasSortAggregationAndHasMany) {\n if (sortProperty === fieldPath) {\n resolvedSortProperty = `_id._field`\n } else {\n resolvedSortProperty = `_id._sort`\n }\n } else {\n resolvedSortProperty = sortProperty === fieldPath ? '_id' : '_sort'\n }\n\n return { [`${resolvedSortProperty}`]: sortDirection }\n}\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 { where = {} } = args\n\n let 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 config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n includeRelationships: true,\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 let sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n let currentFields = collectionConfig.flattenedFields\n let foundField: FlattenedField | null = null\n\n let rels: {\n fieldPath: string\n relationTo: string\n }[] = []\n\n let tempPath = ''\n let insideRelation = false\n\n const segments = args.field.split('.')\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n const field = currentFields.find((e) => e.name === segment)\n if (rels.length) {\n insideRelation = true\n }\n\n if (!field) {\n break\n }\n\n if (tempPath) {\n tempPath = `${tempPath}.${field.name}`\n } else {\n tempPath = field.name\n }\n\n if ('flattenedFields' in field) {\n currentFields = field.flattenedFields\n continue\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n typeof field.relationTo === 'string'\n ) {\n if (i === segments.length - 2 && segments[i + 1] === 'id') {\n foundField = field\n fieldPath = tempPath\n break\n }\n rels.push({ fieldPath: tempPath, relationTo: field.relationTo })\n currentFields = this.payload.collections[field.relationTo]?.config\n .flattenedFields as FlattenedField[]\n continue\n }\n foundField = field\n }\n\n const resolvedField = foundField || fieldPathResult?.field\n const isHasManyValue = resolvedField && 'hasMany' in resolvedField && resolvedField\n\n let relationLookup: null | PipelineStage[] = null\n\n if (!insideRelation) {\n rels = []\n }\n\n if (rels.length) {\n if (sortProperty.startsWith('_')) {\n const sortWithoutRelationPrefix = sortProperty.replace(/^_+/, '')\n const lastFieldPath = rels.at(-1)?.fieldPath as string\n if (sortWithoutRelationPrefix.startsWith(lastFieldPath)) {\n sortProperty = sortWithoutRelationPrefix\n }\n }\n relationLookup = rels.reduce<PipelineStage[]>((acc, { fieldPath, relationTo }) => {\n sortAggregation = sortAggregation.filter((each) => {\n if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {\n return false\n }\n\n return true\n })\n const { Model: foreignModel } = getCollection({ adapter: this, collectionSlug: relationTo })\n acc.push({\n $lookup: {\n as: fieldPath,\n foreignField: '_id',\n from: foreignModel.collection.name,\n localField: fieldPath,\n },\n })\n acc.push({ $unwind: `$${fieldPath}` })\n return acc\n }, [])\n }\n\n let $unwind: any = ''\n let $group: any = null\n if (\n isHasManyValue &&\n sortAggregation.length &&\n sortAggregation[0] &&\n '$lookup' in sortAggregation[0]\n ) {\n $unwind = { path: `$${sortAggregation[0].$lookup.as}`, preserveNullAndEmptyArrays: true }\n $group = {\n _id: {\n _field: `$${sortAggregation[0].$lookup.as}._id`,\n _sort: `$${sortProperty}`,\n },\n }\n } else if (isHasManyValue) {\n $unwind = { path: `$${args.field}`, preserveNullAndEmptyArrays: true }\n }\n\n if (!$group) {\n $group = {\n _id: `$${fieldPath}`,\n ...(sortProperty === fieldPath\n ? {}\n : {\n _sort: { $max: `$${sortProperty}` },\n }),\n }\n }\n\n const pipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n {\n $sort: getSortAggregation({\n fieldPath,\n hasSortAggregationAndHasMany: Boolean(isHasManyValue) && Boolean(sortAggregation.length),\n sortDirection,\n sortProperty,\n }),\n },\n ]\n\n const session = await getSession(this, args.req)\n\n const getValues = async () => {\n return Model.aggregate(pipeline, { session }).then((res) =>\n res.map((each) => ({\n [args.field]: JSON.parse(JSON.stringify(sanitizeGroupID(each._id))),\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\n // Build count pipeline with the same structure as the main pipeline\n // to ensure relationship lookups are included\n const countPipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n { $count: 'count' },\n ]\n\n const totalDocs = await Model.aggregate(countPipeline, {\n session,\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","sanitizeGroupID","id","_field","getSortAggregation","fieldPath","hasSortAggregationAndHasMany","sortDirection","sortProperty","resolvedSortProperty","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","where","sortAggregation","sort","config","payload","fields","flattenedFields","locale","field","timestamps","query","fieldPathResult","includeRelationships","path","pathHasLocalized","localizedPath","replace","page","Object","keys","currentFields","foundField","rels","tempPath","insideRelation","segments","split","i","length","segment","find","e","name","type","relationTo","push","collections","resolvedField","isHasManyValue","relationLookup","startsWith","sortWithoutRelationPrefix","lastFieldPath","at","reduce","acc","filter","each","$lookup","as","foreignModel","foreignField","from","localField","$unwind","$group","preserveNullAndEmptyArrays","_id","_sort","$max","pipeline","$match","$sort","Boolean","session","req","getValues","aggregate","then","res","map","JSON","parse","stringify","limit","$skip","$limit","countPipeline","$count","totalDocs","count","totalPages","Math","ceil","hasPrevPage","hasNextPage","pagingCounter","nextPage","prevPage","values"],"mappings":"AAGA,SAASA,cAAc,QAAQ,UAAS;AAIxC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,MAAMC,kBAAkB,CAACC;IACvB,IAAIA,MAAM,OAAOA,OAAO,YAAY,YAAYA,IAAI;QAClD,OAAOA,GAAGC,MAAM;IAClB;IAEA,OAAOD;AACT;AAEA,MAAME,qBAAqB,CAAC,EAC1BC,SAAS,EACTC,4BAA4B,EAC5BC,aAAa,EACbC,YAAY,EAMb;IACC,IAAIC;IAEJ,IAAIH,8BAA8B;QAChC,IAAIE,iBAAiBH,WAAW;YAC9BI,uBAAuB,CAAC,UAAU,CAAC;QACrC,OAAO;YACLA,uBAAuB,CAAC,SAAS,CAAC;QACpC;IACF,OAAO;QACLA,uBAAuBD,iBAAiBH,YAAY,QAAQ;IAC9D;IAEA,OAAO;QAAE,CAAC,GAAGI,sBAAsB,CAAC,EAAEF;IAAc;AACtD;AAEA,OAAO,MAAMG,eAA6B,eAAuCC,IAAI;IACnF,MAAM,EAAEC,gBAAgB,EAAEC,KAAK,EAAE,GAAGd,cAAc;QAChDe,SAAS,IAAI;QACbC,gBAAgBJ,KAAKK,UAAU;IACjC;IAEA,MAAM,EAAEC,QAAQ,CAAC,CAAC,EAAE,GAAGN;IAEvB,IAAIO,kBAAmC,EAAE;IAEzC,MAAMC,OAAOrB,eAAe;QAC1BgB,SAAS,IAAI;QACbM,QAAQ,IAAI,CAACC,OAAO,CAACD,MAAM;QAC3BE,QAAQV,iBAAiBW,eAAe;QACxCC,QAAQb,KAAKa,MAAM;QACnBL,MAAMR,KAAKQ,IAAI,IAAIR,KAAKc,KAAK;QAC7BP;QACAQ,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3B,MAAMoE,cAAcJ,aAAahE;QACjC,MAAMqE,gBAAgB,AAACrE,CAAAA,OAAO,CAAA,IAAKvB,KAAKgF,KAAK,GAAG;QAEhD,OAAO;YACLW;YACAD;YACAV,OAAOhF,KAAKgF,KAAK;YACjBa,UAAUF,cAAcpE,OAAO,IAAI;YACnCA;YACAqE;YACAE,UAAUJ,cAAcnE,OAAO,IAAI;YACnC8D;YACAE;YACAQ,QAAQ,MAAMvB;QAChB;IACF;IAEA,MAAMuB,SAAS,MAAMvB;IAErB,OAAO;QACLmB,aAAa;QACbD,aAAa;QACbV,OAAO;QACPzD,MAAM;QACNqE,eAAe;QACfP,WAAWU,OAAO7D,MAAM;QACxBqD,YAAY;QACZQ;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../src/findDistinct.ts"],"sourcesContent":["import type { PipelineStage } from 'mongoose'\nimport type { FindDistinct, FlattenedField } from 'payload'\n\nimport { 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\nconst sanitizeGroupID = (id: any) => {\n if (id && typeof id === 'object' && '_field' in id) {\n return id._field\n }\n\n return id\n}\n\nconst getSortAggregation = ({\n fieldPath,\n hasSortAggregationAndHasMany,\n sortDirection,\n sortProperty,\n}: {\n fieldPath: string\n hasSortAggregationAndHasMany: boolean\n sortDirection: -1 | 1\n sortProperty: string\n}): Record<string, -1 | 1> => {\n let resolvedSortProperty: string\n\n if (hasSortAggregationAndHasMany) {\n if (sortProperty === fieldPath) {\n resolvedSortProperty = `_id._field`\n } else {\n resolvedSortProperty = `_id._sort`\n }\n } else {\n resolvedSortProperty = sortProperty === fieldPath ? '_id' : '_sort'\n }\n\n return { [`${resolvedSortProperty}`]: sortDirection }\n}\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 { where = {} } = args\n\n let 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 config: this.payload.config,\n fields: collectionConfig.flattenedFields,\n includeRelationships: true,\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 let sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.\n const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1\n\n let currentFields = collectionConfig.flattenedFields\n let foundField: FlattenedField | null = null\n\n let rels: {\n fieldPath: string\n relationTo: string\n }[] = []\n\n let tempPath = ''\n let insideRelation = false\n\n const segments = args.field.split('.')\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]\n const field = currentFields.find((e) => e.name === segment)\n if (rels.length) {\n insideRelation = true\n }\n\n if (!field) {\n break\n }\n\n if (tempPath) {\n tempPath = `${tempPath}.${field.name}`\n } else {\n tempPath = field.name\n }\n\n if ('flattenedFields' in field) {\n currentFields = field.flattenedFields\n continue\n }\n\n if (\n (field.type === 'relationship' || field.type === 'upload') &&\n typeof field.relationTo === 'string'\n ) {\n if (i === segments.length - 2 && segments[i + 1] === 'id') {\n foundField = field\n fieldPath = tempPath\n break\n }\n rels.push({ fieldPath: tempPath, relationTo: field.relationTo })\n currentFields = this.payload.collections[field.relationTo]?.config\n .flattenedFields as FlattenedField[]\n continue\n }\n foundField = field\n }\n\n const resolvedField = foundField || fieldPathResult?.field\n const isHasManyValue = resolvedField && 'hasMany' in resolvedField && resolvedField\n\n let relationLookup: null | PipelineStage[] = null\n\n if (!insideRelation) {\n rels = []\n }\n\n if (rels.length) {\n if (sortProperty.startsWith('_')) {\n const sortWithoutRelationPrefix = sortProperty.replace(/^_+/, '')\n const lastFieldPath = rels.at(-1)?.fieldPath as string\n if (sortWithoutRelationPrefix.startsWith(lastFieldPath)) {\n sortProperty = sortWithoutRelationPrefix\n }\n }\n relationLookup = []\n for (const { fieldPath, relationTo } of rels) {\n sortAggregation = sortAggregation.filter((each) => {\n if ('$lookup' in each && each.$lookup.as.replace(/^_+/, '') === fieldPath) {\n return false\n }\n\n return true\n })\n const { collectionConfig: foreignCollectionConfig, Model: foreignModel } = getCollection({\n adapter: this,\n collectionSlug: relationTo,\n })\n const relatedAccess = args.relatedAccess?.[fieldPath]\n const relatedAccessQuery = relatedAccess\n ? await buildQuery({\n adapter: this,\n collectionSlug: relationTo,\n fields: foreignCollectionConfig.flattenedFields,\n locale: args.locale,\n where: relatedAccess,\n })\n : null\n\n relationLookup.push({\n $lookup: {\n as: fieldPath,\n from: foreignModel.collection.name,\n ...(relatedAccessQuery\n ? {\n let: { relatedIDs: `$${fieldPath}` },\n pipeline: [\n {\n $match: {\n $and: [\n {\n $expr: {\n $cond: {\n else: { $eq: ['$_id', '$$relatedIDs'] },\n if: { $isArray: '$$relatedIDs' },\n then: { $in: ['$_id', '$$relatedIDs'] },\n },\n },\n },\n relatedAccessQuery,\n ],\n },\n },\n ],\n }\n : {\n foreignField: '_id',\n localField: fieldPath,\n }),\n },\n })\n relationLookup.push({ $unwind: `$${fieldPath}` })\n }\n }\n\n let $unwind: any = ''\n let $group: any = null\n if (\n isHasManyValue &&\n sortAggregation.length &&\n sortAggregation[0] &&\n '$lookup' in sortAggregation[0]\n ) {\n $unwind = { path: `$${sortAggregation[0].$lookup.as}`, preserveNullAndEmptyArrays: true }\n $group = {\n _id: {\n _field: `$${sortAggregation[0].$lookup.as}._id`,\n _sort: `$${sortProperty}`,\n },\n }\n } else if (isHasManyValue) {\n $unwind = { path: `$${args.field}`, preserveNullAndEmptyArrays: true }\n }\n\n if (!$group) {\n $group = {\n _id: `$${fieldPath}`,\n ...(sortProperty === fieldPath\n ? {}\n : {\n _sort: { $max: `$${sortProperty}` },\n }),\n }\n }\n\n const pipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n {\n $sort: getSortAggregation({\n fieldPath,\n hasSortAggregationAndHasMany: Boolean(isHasManyValue) && Boolean(sortAggregation.length),\n sortDirection,\n sortProperty,\n }),\n },\n ]\n\n const session = await getSession(this, args.req)\n\n const getValues = async () => {\n return Model.aggregate(pipeline, { session }).then((res) =>\n res.map((each) => ({\n [args.field]: JSON.parse(JSON.stringify(sanitizeGroupID(each._id))),\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\n // Build count pipeline with the same structure as the main pipeline\n // to ensure relationship lookups are included\n const countPipeline: PipelineStage[] = [\n {\n $match: query,\n },\n ...(sortAggregation.length > 0 ? sortAggregation : []),\n ...(relationLookup?.length ? relationLookup : []),\n ...($unwind\n ? [\n {\n $unwind,\n },\n ]\n : []),\n {\n $group,\n },\n { $count: 'count' },\n ]\n\n const totalDocs = await Model.aggregate(countPipeline, {\n session,\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","sanitizeGroupID","id","_field","getSortAggregation","fieldPath","hasSortAggregationAndHasMany","sortDirection","sortProperty","resolvedSortProperty","findDistinct","args","collectionConfig","Model","adapter","collectionSlug","collection","where","sortAggregation","sort","config","payload","fields","flattenedFields","locale","field","timestamps","query","fieldPathResult","includeRelationships","path","pathHasLocalized","localizedPath","replace","page","Object","keys","currentFields","foundField","rels","tempPath","insideRelation","segments","split","i","length","segment","find","e","name","type","relationTo","push","collections","resolvedField","isHasManyValue","relationLookup","startsWith","sortWithoutRelationPrefix","lastFieldPath","at","filter","each","$lookup","as","foreignCollectionConfig","foreignModel","relatedAccess","relatedAccessQuery","from","let","relatedIDs","pipeline","$match","$and","$expr","$cond","else","$eq","if","$isArray","then","$in","foreignField","localField","$unwind","$group","preserveNullAndEmptyArrays","_id","_sort","$max","$sort","Boolean","session","req","getValues","aggregate","res","map","JSON","parse","stringify","limit","$skip","$limit","countPipeline","$count","totalDocs","count","totalPages","Math","ceil","hasPrevPage","hasNextPage","pagingCounter","nextPage","prevPage","values"],"mappings":"AAGA,SAASA,cAAc,QAAQ,UAAS;AAIxC,SAASC,UAAU,QAAQ,0BAAyB;AACpD,SAASC,cAAc,QAAQ,8BAA6B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD,MAAMC,kBAAkB,CAACC;IACvB,IAAIA,MAAM,OAAOA,OAAO,YAAY,YAAYA,IAAI;QAClD,OAAOA,GAAGC,MAAM;IAClB;IAEA,OAAOD;AACT;AAEA,MAAME,qBAAqB,CAAC,EAC1BC,SAAS,EACTC,4BAA4B,EAC5BC,aAAa,EACbC,YAAY,EAMb;IACC,IAAIC;IAEJ,IAAIH,8BAA8B;QAChC,IAAIE,iBAAiBH,WAAW;YAC9BI,uB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,IAAI,CAACJ,YAAYhG,KAAK2F,KAAK;QACnD,MAAMU,cAAc9E,OAAO;QAC3B,MAAM+E,cAAcJ,aAAa3E;QACjC,MAAMgF,gBAAgB,AAAChF,CAAAA,OAAO,CAAA,IAAKvB,KAAK2F,KAAK,GAAG;QAEhD,OAAO;YACLW;YACAD;YACAV,OAAO3F,KAAK2F,KAAK;YACjBa,UAAUF,cAAc/E,OAAO,IAAI;YACnCA;YACAgF;YACAE,UAAUJ,cAAc9E,OAAO,IAAI;YACnCyE;YACAE;YACAQ,QAAQ,MAAMtB;QAChB;IACF;IAEA,MAAMsB,SAAS,MAAMtB;IAErB,OAAO;QACLkB,aAAa;QACbD,aAAa;QACbV,OAAO;QACPpE,MAAM;QACNgF,eAAe;QACfP,WAAWU,OAAOxE,MAAM;QACxBgE,YAAY;QACZQ;IACF;AACF,EAAC"}
|
package/dist/findOne.js
CHANGED
package/dist/findOne.js.map
CHANGED
|
@@ -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 { 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 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 const session = await getSession(this, req)\n const options: AggregateOptions & QueryOptions = {\n lean: true,\n session,\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","query","fields","flattenedFields","projection","aggregate","session","options","lean","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,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,GAAGd,cAAc;QAAEe,SAAS,IAAI;QAAET;IAAe;IAElF,MAAMU,QAAQ,MAAMpB,WAAW;QAC7BmB,SAAS,IAAI;QACbT;QACAW,QAAQJ,iBAAiBK,eAAe;QACxCT;QACAG;IACF;IAEA,MAAMO,aAAapB,0BAA0B;QAC3CgB,SAAS,IAAI;QACbE,QAAQJ,iBAAiBK,eAAe;QACxCP;IACF;IAEA,MAAMS,YAAY,MAAMtB,qBAAqB;QAC3CiB,SAAS,IAAI;QACbV,YAAYC;QACZO;QACAN;QACAC;QACAC;QACAU;QACAH;IACF;IAEA,MAAMK,UAAU,MAAMpB,WAAW,IAAI,EAAES;IACvC,MAAMY,UAA2C;QAC/CC,MAAM;QACNF;IACF;IAEA,IAAIG;IACJ,IAAIJ,
|
|
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 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 const session = await getSession(this, req)\n const options: AggregateOptions & QueryOptions = {\n lean: true,\n session,\n }\n\n let doc\n if (aggregate.length > 0) {\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","query","fields","flattenedFields","projection","aggregate","session","options","lean","doc","length","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,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,GAAGd,cAAc;QAAEe,SAAS,IAAI;QAAET;IAAe;IAElF,MAAMU,QAAQ,MAAMpB,WAAW;QAC7BmB,SAAS,IAAI;QACbT;QACAW,QAAQJ,iBAAiBK,eAAe;QACxCT;QACAG;IACF;IAEA,MAAMO,aAAapB,0BAA0B;QAC3CgB,SAAS,IAAI;QACbE,QAAQJ,iBAAiBK,eAAe;QACxCP;IACF;IAEA,MAAMS,YAAY,MAAMtB,qBAAqB;QAC3CiB,SAAS,IAAI;QACbV,YAAYC;QACZO;QACAN;QACAC;QACAC;QACAU;QACAH;IACF;IAEA,MAAMK,UAAU,MAAMpB,WAAW,IAAI,EAAES;IACvC,MAAMY,UAA2C;QAC/CC,MAAM;QACNF;IACF;IAEA,IAAIG;IACJ,IAAIJ,UAAUK,MAAM,GAAG,GAAG;QACxB,MAAM,EAAEC,IAAI,EAAE,GAAG,MAAM7B,kBAAkB;YACvCkB,SAAS,IAAI;YACbY,iBAAiBP;YACjBQ,OAAO;YACPd;YACAe,YAAY;YACZV;YACAH;YACAK;QACF;QACAG,MAAME,IAAI,CAAC,EAAE;IACf,OAAO;;QACHJ,QAAoCH,UAAU,GAAGA;QACnDK,MAAM,MAAMV,MAAMV,OAAO,CAACY,OAAO,CAAC,GAAGM;IACvC;IAEA,IAAIE,OAAO,CAAC,IAAI,CAACM,mBAAmB,EAAE;QACpC,MAAM5B,aAAa;YACjBa,SAAS,IAAI;YACbT;YACAoB,MAAM;gBAACF;aAAI;YACXhB;YACAC;QACF;IACF;IAEA,IAAI,CAACe,KAAK;QACR,OAAO;IACT;IAEArB,UAAU;QAAEY,SAAS,IAAI;QAAEgB,MAAMP;QAAKP,QAAQJ,iBAAiBI,MAAM;QAAEe,WAAW;IAAO;IAEzF,OAAOR;AACT,EAAC"}
|
package/dist/migrateFresh.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { MigrationResult } from 'payload';
|
|
1
2
|
import type { MongooseAdapter } from './index.js';
|
|
2
3
|
/**
|
|
3
4
|
* Drop the current database and run all migrate up functions
|
|
4
5
|
*/
|
|
5
|
-
export declare function migrateFresh(this: MongooseAdapter, { forceAcceptWarning }: {
|
|
6
|
+
export declare function migrateFresh(this: MongooseAdapter, { forceAcceptWarning, shouldPrompt, }: {
|
|
6
7
|
forceAcceptWarning?: boolean;
|
|
7
|
-
|
|
8
|
+
shouldPrompt?: boolean;
|
|
9
|
+
}): Promise<MigrationResult>;
|
|
8
10
|
//# sourceMappingURL=migrateFresh.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrateFresh.d.ts","sourceRoot":"","sources":["../src/migrateFresh.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"migrateFresh.d.ts","sourceRoot":"","sources":["../src/migrateFresh.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAK9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD;;GAEG;AACH,wBAAsB,YAAY,CAChC,IAAI,EAAE,eAAe,EACrB,EACE,kBAA0B,EAC1B,YAAmB,GACpB,EAAE;IAAE,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,OAAO,CAAA;CAAE,GAC1D,OAAO,CAAC,eAAe,CAAC,CAiE1B"}
|
package/dist/migrateFresh.js
CHANGED
|
@@ -2,21 +2,28 @@ import { commitTransaction, initTransaction, killTransaction, readMigrationFiles
|
|
|
2
2
|
import prompts from 'prompts';
|
|
3
3
|
/**
|
|
4
4
|
* Drop the current database and run all migrate up functions
|
|
5
|
-
*/ export async function migrateFresh({ forceAcceptWarning = false }) {
|
|
5
|
+
*/ export async function migrateFresh({ forceAcceptWarning = false, shouldPrompt = true }) {
|
|
6
6
|
const { payload } = this;
|
|
7
7
|
if (!forceAcceptWarning) {
|
|
8
|
+
if (!shouldPrompt) {
|
|
9
|
+
return {
|
|
10
|
+
cancelled: true,
|
|
11
|
+
migrated: [],
|
|
12
|
+
rolledBack: []
|
|
13
|
+
};
|
|
14
|
+
}
|
|
8
15
|
const { confirm: acceptWarning } = await prompts({
|
|
9
16
|
name: 'confirm',
|
|
10
17
|
type: 'confirm',
|
|
11
18
|
initial: false,
|
|
12
19
|
message: `WARNING: This will drop your database and run all migrations. Are you sure you want to proceed?`
|
|
13
|
-
}, {
|
|
14
|
-
onCancel: ()=>{
|
|
15
|
-
process.exit(0);
|
|
16
|
-
}
|
|
17
20
|
});
|
|
18
21
|
if (!acceptWarning) {
|
|
19
|
-
|
|
22
|
+
return {
|
|
23
|
+
cancelled: true,
|
|
24
|
+
migrated: [],
|
|
25
|
+
rolledBack: []
|
|
26
|
+
};
|
|
20
27
|
}
|
|
21
28
|
}
|
|
22
29
|
payload.logger.info({
|
|
@@ -32,6 +39,7 @@ import prompts from 'prompts';
|
|
|
32
39
|
const req = {
|
|
33
40
|
payload
|
|
34
41
|
};
|
|
42
|
+
const migrated = [];
|
|
35
43
|
// Run all migrate up
|
|
36
44
|
for (const migration of migrationFiles){
|
|
37
45
|
payload.logger.info({
|
|
@@ -53,6 +61,7 @@ import prompts from 'prompts';
|
|
|
53
61
|
req
|
|
54
62
|
});
|
|
55
63
|
await commitTransaction(req);
|
|
64
|
+
migrated.push(migration.name);
|
|
56
65
|
payload.logger.info({
|
|
57
66
|
msg: `Migrated: ${migration.name} (${Date.now() - start}ms)`
|
|
58
67
|
});
|
|
@@ -65,6 +74,11 @@ import prompts from 'prompts';
|
|
|
65
74
|
throw err;
|
|
66
75
|
}
|
|
67
76
|
}
|
|
77
|
+
return {
|
|
78
|
+
batch: 1,
|
|
79
|
+
migrated,
|
|
80
|
+
rolledBack: []
|
|
81
|
+
};
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
//# sourceMappingURL=migrateFresh.js.map
|