@cyberskill/shared 3.6.0 → 3.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config/vitest/vitest.e2e.js +1 -1
- package/dist/config/vitest/vitest.e2e.js.map +1 -1
- package/dist/config/vitest/vitest.unit.js +1 -1
- package/dist/config/vitest/vitest.unit.js.map +1 -1
- package/dist/constant/common.d.ts +3 -2
- package/dist/constant/common.js +1 -1
- package/dist/constant/common.js.map +1 -1
- package/dist/node/apollo-server/apollo-server.util.js +15 -13
- package/dist/node/apollo-server/apollo-server.util.js.map +1 -1
- package/dist/node/command/command.util.js +29 -29
- package/dist/node/command/command.util.js.map +1 -1
- package/dist/node/express/express.util.d.ts +4 -0
- package/dist/node/express/express.util.js +7 -6
- package/dist/node/express/express.util.js.map +1 -1
- package/dist/node/mongo/mongo.controller.mongoose.d.ts +6 -1
- package/dist/node/mongo/mongo.controller.mongoose.js +10 -11
- package/dist/node/mongo/mongo.controller.mongoose.js.map +1 -1
- package/dist/node/mongo/mongo.controller.native.d.ts +1 -1
- package/dist/node/mongo/mongo.controller.native.js +5 -4
- package/dist/node/mongo/mongo.controller.native.js.map +1 -1
- package/dist/node/mongo/mongo.controller.type.d.ts +15 -0
- package/dist/node/mongo/mongo.dynamic-populate.js +12 -12
- package/dist/node/mongo/mongo.dynamic-populate.js.map +1 -1
- package/dist/node/mongo/mongo.util.d.ts +3 -3
- package/dist/node/mongo/mongo.util.js.map +1 -1
- package/dist/node/path/index.js +2 -2
- package/dist/node/path/path.constant.d.ts +21 -7
- package/dist/node/path/path.constant.js +48 -29
- package/dist/node/path/path.constant.js.map +1 -1
- package/dist/node/storage/storage.util.js +2 -6
- package/dist/node/storage/storage.util.js.map +1 -1
- package/dist/node/ws/ws.util.js +2 -0
- package/dist/node/ws/ws.util.js.map +1 -1
- package/dist/react/apollo-client/apollo-client.util.js +42 -41
- package/dist/react/apollo-client/apollo-client.util.js.map +1 -1
- package/dist/react/log/log.util.d.ts +5 -0
- package/dist/react/log/log.util.js.map +1 -1
- package/dist/typescript/common.type.d.ts +18 -0
- package/dist/typescript/common.type.js +9 -2
- package/dist/typescript/common.type.js.map +1 -1
- package/dist/typescript/index.js +2 -2
- package/dist/util/object/object.util.js +43 -37
- package/dist/util/object/object.util.js.map +1 -1
- package/dist/util/serializer/serializer.util.d.ts +13 -0
- package/dist/util/serializer/serializer.util.js.map +1 -1
- package/dist/util/string/string.util.js +45 -13
- package/dist/util/string/string.util.js.map +1 -1
- package/package.json +7 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongo.controller.mongoose.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.mongoose.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\nimport { normalizeMongoFilter } from '#util/index.js';\nimport { generateRandomString, generateShortId, generateSlug } from '#util/string/index.js';\n\nimport type { C_Document, I_DeleteOptionsExtended, I_DynamicVirtualConfig, I_ExtendedModel, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Input_Populate, T_InsertManyOptions, T_PaginateResult, T_PipelineStage, T_PopulateOptions, T_ProjectionType, T_QueryFilter, T_QueryOptions, T_UpdateQuery, T_UpdateResult } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { MONGO_SLUG_MAX_ATTEMPTS } from './mongo.constant.js';\nimport { filterDynamicVirtualsFromPopulate, isObject, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\n\n/**\n * Converts a Mongoose document to a plain object, handling the case where\n * the document may already be a plain object (e.g., from `.lean()`).\n *\n * @param doc - The document or plain object.\n * @returns The plain object representation.\n */\nfunction toPlainObject<T>(doc: T): T {\n return (doc as T & { toObject?: () => T })?.toObject?.() ?? doc;\n}\n\n/** Internal shape of a single virtual config stored on the model. */\ninterface I_VirtualConfig {\n name: string;\n options?: { ref?: unknown };\n}\n\n/**\n * Mongoose controller for database operations with advanced features.\n * This class provides a comprehensive interface for Mongoose operations including\n * pagination, aggregation, slug generation, and short ID creation.\n */\nexport class MongooseController<T extends Partial<C_Document>> {\n private defaultLimit: number;\n\n /**\n * Creates a new Mongoose controller instance.\n *\n * @param model - The Mongoose model to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 10,000).\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number }) {\n this.defaultLimit = options?.defaultLimit ?? 10_000;\n }\n\n /**\n * Gets the model name for logging and error messages.\n *\n * @returns The name of the model.\n */\n private getModelName(): string {\n return this.model.modelName;\n }\n\n /**\n * Gets the dynamic virtuals configuration from the model instance.\n *\n * @returns Array of dynamic virtual configurations or undefined if none exist.\n */\n private getDynamicVirtuals(): I_DynamicVirtualConfig<T>[] | undefined {\n const model = this.model as I_ExtendedModel<T> & { _virtualConfigs?: I_VirtualConfig[] };\n\n if (model._virtualConfigs) {\n const dynamicOnly = model._virtualConfigs.filter(\n v => typeof v.options?.ref === 'function',\n ) as unknown as I_DynamicVirtualConfig<T>[];\n\n if (dynamicOnly.length > 0) {\n return dynamicOnly;\n }\n }\n\n const schemaStatics = this.model.schema.statics as { [key: string]: unknown };\n\n return schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[] | undefined;\n }\n\n /**\n * Populates dynamic virtuals for a single document.\n *\n * @param result - The document to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The document with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocument(result: T, populate?: T_Input_Populate): Promise<T> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedArr = await populateDynamicVirtuals(this.model.base, [result], dynamicVirtuals, populate, undefined, this.model);\n\n return (populatedArr && populatedArr[0]) ? populatedArr[0] as T : result;\n }\n\n return result;\n }\n\n /**\n * Populates dynamic virtuals for an array of documents.\n *\n * @param results - The documents to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The documents with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocuments(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n const populatedResults = await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\n\n return populatedResults;\n }\n\n return results;\n }\n\n /**\n * Finds a single document with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find the document.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.findOne(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n const finalResult = await this.populateDynamicVirtualsForDocument(result, populate);\n\n return { success: true, result: toPlainObject(finalResult) };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Finds all documents with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T[]>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.find(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n\n if (!options.limit) {\n query.limit(this.defaultLimit);\n }\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n const finalResult = await this.populateDynamicVirtualsForDocuments(result, populate);\n\n if (finalResult.length === this.defaultLimit && !options.limit) {\n log.warn(`[${this.getModelName()}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return { success: true, result: finalResult.map(item => toPlainObject(item)) };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Finds documents with pagination support.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param options - Pagination options including page, limit, and population.\n * @returns A promise that resolves to a standardized response with paginated results.\n */\n async findPaging(\n filter: T_QueryFilter<T> = {},\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_PaginateResult<T>>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.paginate(normalizedFilter, filteredOptions);\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: populatedDocs.map(item => toPlainObject(item)) } };\n }\n\n return { success: true, result: { ...result, docs: result.docs.map(item => toPlainObject(item)) } };\n }\n catch (error) {\n return catchError<T_PaginateResult<T>>(error);\n }\n }\n\n /**\n * Performs aggregation with pagination support.\n *\n * @param pipeline - The aggregation pipeline stages.\n * @param options - Pagination options for the aggregation result.\n * @returns A promise that resolves to a standardized response with paginated aggregation results.\n */\n async findPagingAggregate(\n pipeline: T_PipelineStage[],\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_AggregatePaginateResult<T>>> {\n try {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.aggregatePaginate(\n this.model.aggregate(pipeline),\n filteredOptions,\n );\n\n const finalDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: finalDocs.map(item => item?.toObject?.() ?? item) } };\n }\n catch (error) {\n return catchError<T_AggregatePaginateResult<T>>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents.\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(filter: T_QueryFilter<T> = {}): Promise<I_Return<number>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.countDocuments(normalizedFilter);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Creates a single document.\n *\n * @param doc - The document to create.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(doc: T | Partial<T>): Promise<I_Return<T>> {\n try {\n const result = await this.model.create(doc as unknown as Parameters<typeof this.model.create>[0]);\n\n return { success: true, result: (result as T)?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Creates multiple documents with bulk insertion.\n *\n * @param docs - An array of documents to create.\n * @param options - Options for the bulk insertion operation.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(\n docs: (T | Partial<T>)[],\n options: T_InsertManyOptions = {},\n ): Promise<I_Return<T[]>> {\n try {\n const createdDocuments = await this.model.insertMany(docs, options);\n\n return { success: true, result: createdDocuments.map(item => item?.toObject?.() ?? item) as T[] };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Updates a single document and returns the updated version.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the updated document.\n */\n async updateOne(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndUpdate(normalizedFilter, update, {\n new: true,\n ...options,\n })\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `Failed to update ${this.getModelName()}.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .updateMany(normalizedFilter, update, options)\n .exec();\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document and returns the deleted version.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the deleted document.\n */\n async deleteOne(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndDelete(normalizedFilter, options)\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.deleteMany(normalizedFilter, options).exec();\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: `No documents found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Creates a unique short ID based on a given ID.\n * This method generates multiple short IDs with increasing lengths and finds the first available one.\n *\n * @param id - The base ID to generate short IDs from.\n * @param length - The initial length for short ID generation (default: 4).\n * @returns A promise that resolves to a standardized response with the unique short ID.\n */\n async createShortId(id: string, length = 4): Promise<I_Return<string>> {\n try {\n const maxRetries = 10;\n const shortIds = Array.from({ length: maxRetries }, (_, index) =>\n generateShortId(id, index + length));\n\n // Use a single $in query instead of 10 parallel exists() calls\n const existingDocs = await this.model\n .find({ shortId: { $in: shortIds } })\n .select('shortId')\n .lean();\n\n const existingShortIds = new Set(\n existingDocs.map((d: Record<string, unknown>) => d['shortId'] as string),\n );\n\n const availableShortId = shortIds.find(s => !existingShortIds.has(s));\n\n if (availableShortId) {\n return { success: true, result: availableShortId };\n }\n\n return {\n success: false,\n message: 'Failed to create a unique shortId',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n catch (error) {\n return catchError<string>(error);\n }\n }\n\n /**\n * Creates a query for slug existence checking.\n * This method generates a query that checks for slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug query generation including slug, field, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A MongoDB query object for checking slug existence.\n */\n createSlugQuery({ slug, field, isObject, haveHistory = false, filter }: I_Input_GenerateSlug<T>) {\n const baseFilter = { ...(filter ?? {}) };\n\n return isObject\n ? {\n ...baseFilter,\n $or: [\n { [`slug.${field}`]: slug },\n ...(haveHistory ? [{ slugHistory: { $elemMatch: { [`slug.${field}`]: slug } } }] : []),\n ],\n }\n : {\n ...baseFilter,\n $or: [\n { slug },\n ...(haveHistory ? [{ slugHistory: slug }] : []),\n ],\n };\n }\n\n /**\n * Creates a unique slug based on a given string.\n * This method generates multiple slug variations and finds the first available one.\n *\n * @param options - Configuration for slug generation including slug, field, and filter.\n * @param options.slug - The base slug string to make unique.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a unique slug string.\n */\n async createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string> {\n if (!slug || typeof slug !== 'string') {\n throw new Error('Invalid slug provided: must be a non-empty string');\n }\n\n const baseSlug = generateSlug(slug);\n\n const baseExists = await this.model.exists(\n this.createSlugQuery({ slug: baseSlug, field, isObject, haveHistory, filter }),\n );\n\n if (!baseExists) {\n return baseSlug;\n }\n\n // Batch query: check all slug variations in a single database call instead of N+1 sequential queries\n const variants = Array.from(\n { length: MONGO_SLUG_MAX_ATTEMPTS },\n (_, i) => `${baseSlug}-${i + 1}`,\n );\n\n const slugQueries = variants.map(s =>\n this.createSlugQuery({ slug: s, field, isObject, haveHistory, filter }),\n );\n\n const slugField = isObject ? `slug.${field as string}` : 'slug';\n const existingDocs = await this.model\n .find({ $or: slugQueries.map(q => q.$or).flat() })\n .select(slugField)\n .lean();\n\n const existingSlugs = new Set(\n existingDocs.map((d: Record<string, unknown>) => {\n if (isObject) {\n const slug = d['slug'] as Record<string, unknown> | undefined;\n return slug?.[field as string];\n }\n return d['slug'];\n }),\n );\n\n const available = variants.find(s => !existingSlugs.has(s));\n\n if (available) {\n return available;\n }\n\n const timestamp = Date.now();\n const randomSuffix = generateRandomString(6);\n\n return `${baseSlug}-${timestamp}-${randomSuffix}`;\n }\n\n /**\n * Creates a slug for a document field.\n * This method handles both simple string fields and object fields with nested slug generation.\n *\n * @param options - Configuration for slug creation including field, source document, and filter.\n * @param options.field - The field name to create a slug for.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a standardized response with the created slug(s).\n */\n async createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const uniqueSlug = Object.fromEntries(\n await Promise.all(\n Object.entries(fieldValue).map(async ([key, value]) => {\n const uniqueSlugForKey = await this.createUniqueSlug({\n slug: value as string,\n field: key,\n isObject: true,\n haveHistory,\n filter,\n });\n return [key, uniqueSlugForKey];\n }),\n ),\n );\n\n return { success: true, result: uniqueSlug as R };\n }\n\n const uniqueSlug = await this.createUniqueSlug({\n slug: fieldValue as string,\n field,\n isObject: false,\n haveHistory,\n filter,\n });\n\n return { success: true, result: uniqueSlug as R };\n }\n catch (error) {\n return catchError<R>(error);\n }\n }\n\n /**\n * Checks if a slug already exists in the collection.\n * This method verifies slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug checking including slug, field, source document, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A promise that resolves to a standardized response indicating whether the slug exists.\n */\n async checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const values = Object.values(fieldValue);\n const nestedSlugs = values.map(value => generateSlug(value as string));\n\n const existenceChecks = await Promise.all(\n nestedSlugs.map(nestedSlug =>\n this.model.exists(this.createSlugQuery({\n slug: nestedSlug,\n field,\n isObject: true,\n haveHistory,\n filter,\n })),\n ),\n );\n\n if (existenceChecks.some(exists => exists)) {\n return { success: true, result: true };\n }\n\n return { success: true, result: false };\n }\n\n const baseSlug = generateSlug(slug);\n const exists = await this.model.exists(this.createSlugQuery({\n slug: baseSlug,\n field,\n isObject: false,\n filter,\n }));\n\n return { success: true, result: exists !== null };\n }\n catch (error) {\n return catchError<boolean>(error);\n }\n }\n\n /**\n * Performs aggregation operations on the collection.\n *\n * @param pipeline - The aggregation pipeline stages to execute.\n * @returns A promise that resolves to a standardized response with the aggregation results.\n */\n async aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>> {\n try {\n const result = await this.model.aggregate<T>(pipeline);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Retrieves distinct values for the specified key from the collection.\n *\n * @param key - The field for which to return distinct values.\n * @param filter - The filter query to apply (optional).\n * @param options - Additional options for the distinct operation (optional).\n * @returns A promise that resolves to a standardized response with the array of distinct values.\n */\n async distinct(\n key: string,\n filter: T_QueryFilter<T> = {},\n options: T_QueryOptions<T> = {},\n ): Promise<I_Return<unknown[]>> {\n try {\n const result = await this.model.distinct(key, filter, options);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<unknown[]>(error);\n }\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAS,EAAiB,GAAW;AACjC,QAAQ,GAAoC,YAAY,IAAI;;AAchE,IAAa,IAAb,MAA+D;CAC3D;CASA,YAAY,GAAmC,GAAqC;AAChF,EADgB,KAAA,QAAA,GAChB,KAAK,eAAe,GAAS,gBAAgB;;CAQjD,eAA+B;AAC3B,SAAO,KAAK,MAAM;;CAQtB,qBAAsE;EAClE,IAAM,IAAQ,KAAK;AAEnB,MAAI,EAAM,iBAAiB;GACvB,IAAM,IAAc,EAAM,gBAAgB,QACtC,MAAK,OAAO,EAAE,SAAS,OAAQ,WAClC;AAED,OAAI,EAAY,SAAS,EACrB,QAAO;;AAMf,SAFsB,KAAK,MAAM,OAAO,QAEnB;;CAUzB,MAAc,mCAAmC,GAAW,GAAyC;EACjG,IAAM,IAAkB,KAAK,oBAAoB;AAEjD,MAAI,KAAmB,EAAgB,SAAS,GAAG;GAC/C,IAAM,IAAe,MAAM,EAAwB,KAAK,MAAM,MAAM,CAAC,EAAO,EAAE,GAAiB,GAAU,KAAA,GAAW,KAAK,MAAM;AAE/H,UAAQ,KAAgB,EAAa,KAAM,EAAa,KAAU;;AAGtE,SAAO;;CAUX,MAAc,oCAAoC,GAAc,GAA2C;EACvG,IAAM,IAAkB,KAAK,oBAAoB;AAQjD,SANI,KAAmB,EAAgB,SAAS,KAAK,EAAQ,SAAS,IACzC,MAAM,EAAwB,KAAK,MAAM,MAAM,GAAS,GAAiB,GAAU,KAAA,GAAW,KAAK,MAAM,GAK/H;;CAaX,MAAM,QACF,IAA2B,EAAE,EAC7B,IAAkC,EAAE,EACpC,IAA6B,EAAE,EAC/B,GACoB;AACpB,MAAI;GACA,IAAM,IAAmB,EAAqB,EAAO,EAC/C,IAAQ,KAAK,MAAM,QAAQ,GAAkB,GAAY,EAAQ,CAAC,UAAU,IAAO,CAAC,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,GAAQ,EAAQ;IAE9B;WAE7B,GAAO;AACV,UAAO,EAAsB,EAAM"}
|
|
1
|
+
{"version":3,"file":"mongo.controller.mongoose.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.mongoose.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\nimport { normalizeMongoFilter } from '#util/index.js';\nimport { generateRandomString, generateShortId, generateSlug } from '#util/string/index.js';\n\nimport type { C_Document, I_DeleteOptionsExtended, I_DynamicVirtualConfig, I_ExtendedModel, I_Input_CheckSlug, I_Input_CreateSlug, I_Input_GenerateSlug, I_PaginateOptionsWithPopulate, I_UpdateOptionsExtended, T_AggregatePaginateResult, T_DeleteResult, T_Input_Populate, T_InsertManyOptions, T_PaginateResult, T_PipelineStage, T_PopulateOptions, T_ProjectionType, T_QueryFilter, T_QueryOptions, T_UpdateQuery, T_UpdateResult } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { MONGO_SLUG_MAX_ATTEMPTS } from './mongo.constant.js';\nimport { filterDynamicVirtualsFromPopulate, isObject, populateDynamicVirtuals } from './mongo.dynamic-populate.js';\n\n/**\n * Converts a Mongoose document to a plain object, handling the case where\n * the document may already be a plain object (e.g., from `.lean()`).\n *\n * @param doc - The document or plain object.\n * @returns The plain object representation.\n */\nfunction toPlainObject<T>(doc: T): T {\n return (doc as T & { toObject?: () => T })?.toObject?.() ?? doc;\n}\n\n/** Internal shape of a single virtual config stored on the model. */\ninterface I_VirtualConfig {\n name: string;\n options?: { ref?: unknown };\n}\n\n/**\n * Mongoose controller for database operations with advanced features.\n * This class provides a comprehensive interface for Mongoose operations including\n * pagination, aggregation, slug generation, and short ID creation.\n */\nexport class MongooseController<T extends Partial<C_Document>> {\n private defaultLimit: number;\n\n /**\n * Creates a new Mongoose controller instance.\n *\n * @param model - The Mongoose model to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 1,000).\n */\n constructor(private model: I_ExtendedModel<T>, options?: { defaultLimit?: number }) {\n this.defaultLimit = options?.defaultLimit ?? 1_000;\n }\n\n /**\n * Gets the model name for logging and error messages.\n *\n * @returns The name of the model.\n */\n private getModelName(): string {\n return this.model.modelName;\n }\n\n /**\n * Gets the dynamic virtuals configuration from the model instance.\n *\n * @returns Array of dynamic virtual configurations or undefined if none exist.\n */\n private getDynamicVirtuals(): I_DynamicVirtualConfig<T>[] | undefined {\n const model = this.model as I_ExtendedModel<T> & { _virtualConfigs?: I_VirtualConfig[] };\n\n if (model._virtualConfigs) {\n const dynamicOnly = model._virtualConfigs.filter(\n v => typeof v.options?.ref === 'function',\n ) as unknown as I_DynamicVirtualConfig<T>[];\n\n if (dynamicOnly.length > 0) {\n return dynamicOnly;\n }\n }\n\n const schemaStatics = this.model.schema.statics as { [key: string]: unknown };\n\n return schemaStatics['_dynamicVirtuals'] as I_DynamicVirtualConfig<T>[] | undefined;\n }\n\n /**\n * Populates dynamic virtuals for a single document.\n *\n * @param result - The document to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The document with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocument(result: T, populate?: T_Input_Populate): Promise<T> {\n const populated = await this.populateDynamic([result], populate);\n return populated[0] ?? result;\n }\n\n /**\n * Populates dynamic virtuals for an array of documents.\n *\n * @param results - The documents to populate dynamic virtuals for.\n * @param populate - The populate options to determine which virtuals to populate.\n * @returns The documents with dynamic virtuals populated.\n */\n private async populateDynamicVirtualsForDocuments(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n return this.populateDynamic(results, populate);\n }\n\n /**\n * Internal helper that populates dynamic virtuals for an array of documents.\n * Shared implementation used by both single-document and multi-document methods.\n */\n private async populateDynamic(results: T[], populate?: T_Input_Populate): Promise<T[]> {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0 && results.length > 0) {\n return await populateDynamicVirtuals(this.model.base, results, dynamicVirtuals, populate, undefined, this.model) as T[];\n }\n\n return results;\n }\n\n /**\n * Finds a single document with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find the document.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.findOne(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n const finalResult = await this.populateDynamicVirtualsForDocument(result, populate);\n\n return { success: true, result: toPlainObject(finalResult) };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Finds all documents with optional population and projection.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param projection - The fields to include/exclude in the result.\n * @param options - Query options for the operation.\n * @param populate - Population configuration for related documents.\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_QueryFilter<T> = {},\n projection: T_ProjectionType<T> = {},\n options: T_QueryOptions<T> = {},\n populate?: T_Input_Populate,\n ): Promise<I_Return<T[]>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const query = this.model.find(normalizedFilter, projection, options).maxTimeMS(30_000).lean();\n\n if (!options.limit) {\n query.limit(this.defaultLimit);\n }\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const regularPopulate = filterDynamicVirtualsFromPopulate(populate, dynamicVirtuals);\n\n if (regularPopulate) {\n query.populate(regularPopulate as T_PopulateOptions);\n }\n\n const result = await query.exec();\n\n const finalResult = await this.populateDynamicVirtualsForDocuments(result, populate);\n\n const truncated = finalResult.length === this.defaultLimit && !options.limit;\n\n if (truncated) {\n log.warn(`[${this.getModelName()}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return { success: true, result: finalResult.map(item => toPlainObject(item)), truncated };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Finds documents with pagination support.\n * Automatically handles dynamic virtual population if configured.\n *\n * @param filter - The filter criteria to find documents.\n * @param options - Pagination options including page, limit, and population.\n * @returns A promise that resolves to a standardized response with paginated results.\n */\n async findPaging(\n filter: T_QueryFilter<T> = {},\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_PaginateResult<T>>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.paginate(normalizedFilter, filteredOptions);\n\n if (dynamicVirtuals && dynamicVirtuals.length > 0) {\n const populatedDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: populatedDocs.map(item => toPlainObject(item)) } };\n }\n\n return { success: true, result: { ...result, docs: result.docs.map(item => toPlainObject(item)) } };\n }\n catch (error) {\n return catchError<T_PaginateResult<T>>(error);\n }\n }\n\n /**\n * Performs aggregation with pagination support.\n *\n * @param pipeline - The aggregation pipeline stages.\n * @param options - Pagination options for the aggregation result.\n * @returns A promise that resolves to a standardized response with paginated aggregation results.\n */\n async findPagingAggregate(\n pipeline: T_PipelineStage[],\n options: I_PaginateOptionsWithPopulate = {},\n ): Promise<I_Return<T_AggregatePaginateResult<T>>> {\n try {\n const dynamicVirtuals = this.getDynamicVirtuals();\n\n const filteredOptions = { ...options };\n\n if (options.populate) {\n filteredOptions.populate = filterDynamicVirtualsFromPopulate(options.populate, dynamicVirtuals);\n }\n\n const result = await this.model.aggregatePaginate(\n this.model.aggregate(pipeline),\n filteredOptions,\n );\n\n const finalDocs = await this.populateDynamicVirtualsForDocuments(result.docs, options.populate);\n\n return { success: true, result: { ...result, docs: finalDocs.map(item => toPlainObject(item)) } };\n }\n catch (error) {\n return catchError<T_AggregatePaginateResult<T>>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents.\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(filter: T_QueryFilter<T> = {}): Promise<I_Return<number>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.countDocuments(normalizedFilter);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Creates a single document.\n *\n * @param doc - The document to create.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(doc: T | Partial<T>): Promise<I_Return<T>> {\n try {\n const result = await this.model.create(doc as unknown as Parameters<typeof this.model.create>[0]);\n\n return { success: true, result: (result as T)?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Creates multiple documents with bulk insertion.\n *\n * @param docs - An array of documents to create.\n * @param options - Options for the bulk insertion operation.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(\n docs: (T | Partial<T>)[],\n options: T_InsertManyOptions = {},\n ): Promise<I_Return<T[]>> {\n try {\n const createdDocuments = await this.model.insertMany(docs, options);\n\n return { success: true, result: createdDocuments.map(item => item?.toObject?.() ?? item) as T[] };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Updates a single document and returns the updated version.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the updated document.\n */\n async updateOne(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndUpdate(normalizedFilter, update, {\n new: true,\n ...options,\n })\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `Failed to update ${this.getModelName()}.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply.\n * @param options - Options for the update operation.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_QueryFilter<T> = {},\n update: T_UpdateQuery<T> = {},\n options: I_UpdateOptionsExtended = {},\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .updateMany(normalizedFilter, update, options)\n .exec();\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document and returns the deleted version.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the deleted document.\n */\n async deleteOne(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model\n .findOneAndDelete(normalizedFilter, options)\n .exec();\n\n if (!result) {\n return {\n success: false,\n message: `No ${this.getModelName()} found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result: result?.toObject?.() ?? result };\n }\n catch (error) {\n return catchError<T>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @param options - Options for the delete operation.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_QueryFilter<T> = {},\n options: I_DeleteOptionsExtended = {},\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const normalizedFilter = normalizeMongoFilter(filter);\n const result = await this.model.deleteMany(normalizedFilter, options).exec();\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: `No documents found to delete.`,\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Creates a unique short ID based on a given ID.\n * This method generates multiple short IDs with increasing lengths and finds the first available one.\n *\n * @param id - The base ID to generate short IDs from.\n * @param length - The initial length for short ID generation (default: 4).\n * @returns A promise that resolves to a standardized response with the unique short ID.\n */\n async createShortId(id: string, length = 4): Promise<I_Return<string>> {\n try {\n const maxRetries = 10;\n const shortIds = Array.from({ length: maxRetries }, (_, index) =>\n generateShortId(id, index + length));\n\n // Use a single $in query instead of 10 parallel exists() calls\n const existingDocs = await this.model\n .find({ shortId: { $in: shortIds } })\n .select('shortId')\n .lean();\n\n const existingShortIds = new Set(\n existingDocs.map((d: Record<string, unknown>) => d['shortId'] as string),\n );\n\n const availableShortId = shortIds.find(s => !existingShortIds.has(s));\n\n if (availableShortId) {\n return { success: true, result: availableShortId };\n }\n\n return {\n success: false,\n message: 'Failed to create a unique shortId',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n catch (error) {\n return catchError<string>(error);\n }\n }\n\n /**\n * Creates a query for slug existence checking.\n * This method generates a query that checks for slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug query generation including slug, field, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A MongoDB query object for checking slug existence.\n */\n createSlugQuery({ slug, field, isObject, haveHistory = false, filter }: I_Input_GenerateSlug<T>) {\n const baseFilter = { ...(filter ?? {}) };\n\n return isObject\n ? {\n ...baseFilter,\n $or: [\n { [`slug.${field}`]: slug },\n ...(haveHistory ? [{ slugHistory: { $elemMatch: { [`slug.${field}`]: slug } } }] : []),\n ],\n }\n : {\n ...baseFilter,\n $or: [\n { slug },\n ...(haveHistory ? [{ slugHistory: slug }] : []),\n ],\n };\n }\n\n /**\n * Creates a unique slug based on a given string.\n * This method generates multiple slug variations and finds the first available one.\n *\n * @param options - Configuration for slug generation including slug, field, and filter.\n * @param options.slug - The base slug string to make unique.\n * @param options.field - The field name for object-based slug checking.\n * @param options.isObject - Whether the slug is stored as an object with nested fields.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a unique slug string.\n */\n async createUniqueSlug({ slug, field, isObject, haveHistory, filter }: I_Input_GenerateSlug<T>): Promise<string> {\n if (!slug || typeof slug !== 'string') {\n throw new Error('Invalid slug provided: must be a non-empty string');\n }\n\n const baseSlug = generateSlug(slug);\n\n const baseExists = await this.model.exists(\n this.createSlugQuery({ slug: baseSlug, field, isObject, haveHistory, filter }),\n );\n\n if (!baseExists) {\n return baseSlug;\n }\n\n // Batch query: check all slug variations in a single database call instead of N+1 sequential queries\n const variants = Array.from(\n { length: MONGO_SLUG_MAX_ATTEMPTS },\n (_, i) => `${baseSlug}-${i + 1}`,\n );\n\n const slugQueries = variants.map(s =>\n this.createSlugQuery({ slug: s, field, isObject, haveHistory, filter }),\n );\n\n const slugField = isObject ? `slug.${field as string}` : 'slug';\n const existingDocs = await this.model\n .find({ $or: slugQueries.map(q => q.$or).flat() })\n .select(slugField)\n .lean();\n\n const existingSlugs = new Set(\n existingDocs.map((d: Record<string, unknown>) => {\n if (isObject) {\n const slug = d['slug'] as Record<string, unknown> | undefined;\n return slug?.[field as string];\n }\n return d['slug'];\n }),\n );\n\n const available = variants.find(s => !existingSlugs.has(s));\n\n if (available) {\n return available;\n }\n\n const timestamp = Date.now();\n const randomSuffix = generateRandomString(6);\n\n return `${baseSlug}-${timestamp}-${randomSuffix}`;\n }\n\n /**\n * Creates a slug for a document field.\n * This method handles both simple string fields and object fields with nested slug generation.\n *\n * @param options - Configuration for slug creation including field, source document, and filter.\n * @param options.field - The field name to create a slug for.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for uniqueness.\n * @param options.filter - Additional filter conditions to apply when checking slug existence.\n * @returns A promise that resolves to a standardized response with the created slug(s).\n */\n async createSlug<R = string>({ field, from, filter, haveHistory }: I_Input_CreateSlug<T>): Promise<I_Return<R>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const uniqueSlug = Object.fromEntries(\n await Promise.all(\n Object.entries(fieldValue).map(async ([key, value]) => {\n const uniqueSlugForKey = await this.createUniqueSlug({\n slug: value as string,\n field: key,\n isObject: true,\n haveHistory,\n filter,\n });\n return [key, uniqueSlugForKey];\n }),\n ),\n );\n\n return { success: true, result: uniqueSlug as R };\n }\n\n const uniqueSlug = await this.createUniqueSlug({\n slug: fieldValue as string,\n field,\n isObject: false,\n haveHistory,\n filter,\n });\n\n return { success: true, result: uniqueSlug as R };\n }\n catch (error) {\n return catchError<R>(error);\n }\n }\n\n /**\n * Checks if a slug already exists in the collection.\n * This method verifies slug existence in both current and historical slug fields.\n *\n * @param options - Configuration for slug checking including slug, field, source document, and filter.\n * @param options.slug - The slug string to check for existence.\n * @param options.field - The field name for object-based slug checking.\n * @param options.from - The source document containing the field value.\n * @param options.haveHistory - Whether to check historical slug fields for existence.\n * @param options.filter - Additional filter conditions to apply to the query.\n * @returns A promise that resolves to a standardized response indicating whether the slug exists.\n */\n async checkSlug({ slug, field, from, filter, haveHistory }: I_Input_CheckSlug<T>): Promise<I_Return<boolean>> {\n try {\n const fieldValue = from[field as keyof T];\n const isObjectValue = isObject(fieldValue);\n\n if (isObjectValue) {\n const values = Object.values(fieldValue);\n const nestedSlugs = values.map(value => generateSlug(value as string));\n\n const existenceChecks = await Promise.all(\n nestedSlugs.map(nestedSlug =>\n this.model.exists(this.createSlugQuery({\n slug: nestedSlug,\n field,\n isObject: true,\n haveHistory,\n filter,\n })),\n ),\n );\n\n if (existenceChecks.some(exists => exists)) {\n return { success: true, result: true };\n }\n\n return { success: true, result: false };\n }\n\n const baseSlug = generateSlug(slug);\n const exists = await this.model.exists(this.createSlugQuery({\n slug: baseSlug,\n field,\n isObject: false,\n filter,\n }));\n\n return { success: true, result: exists !== null };\n }\n catch (error) {\n return catchError<boolean>(error);\n }\n }\n\n /**\n * Performs aggregation operations on the collection.\n *\n * @param pipeline - The aggregation pipeline stages to execute.\n * @returns A promise that resolves to a standardized response with the aggregation results.\n */\n async aggregate(pipeline: T_PipelineStage[]): Promise<I_Return<T[]>> {\n try {\n const result = await this.model.aggregate<T>(pipeline);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<T[]>(error);\n }\n }\n\n /**\n * Retrieves distinct values for the specified key from the collection.\n *\n * @param key - The field for which to return distinct values.\n * @param filter - The filter query to apply (optional).\n * @param options - Additional options for the distinct operation (optional).\n * @returns A promise that resolves to a standardized response with the array of distinct values.\n */\n async distinct(\n key: string,\n filter: T_QueryFilter<T> = {},\n options: T_QueryOptions<T> = {},\n ): Promise<I_Return<unknown[]>> {\n try {\n const result = await this.model.distinct(key, filter, options);\n\n return { success: true, result };\n }\n catch (error) {\n return catchError<unknown[]>(error);\n }\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAS,EAAiB,GAAW;AACjC,QAAQ,GAAoC,YAAY,IAAI;;AAchE,IAAa,IAAb,MAA+D;CAC3D;CASA,YAAY,GAAmC,GAAqC;AAChF,EADgB,KAAA,QAAA,GAChB,KAAK,eAAe,GAAS,gBAAgB;;CAQjD,eAA+B;AAC3B,SAAO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EAAS,EAAW,EAEvB;IAEf,IAAM,IADS,OAAO,OAAO,EAAW,CACb,KAAI,MAAS,EAAa,EAAgB,CAAC;AAkBtE,YAhBwB,MAAM,QAAQ,IAClC,EAAY,KAAI,MACZ,KAAK,MAAM,OAAO,KAAK,gBAAgB;KACnC,MAAM;KACN;KACA,UAAU;KACV;KACA;KACH,CAAC,CAAC,CACN,CACJ,EAEmB,MAAK,MAAU,EAAO,GAC/B;KAAE,SAAS;KAAM,QAAQ;KAAM,GAGnC;KAAE,SAAS;KAAM,QAAQ;KAAO;;GAG3C,IAAM,IAAW,EAAa,EAAK;AAQnC,UAAO;IAAE,SAAS;IAAM,QAPT,MAAM,KAAK,MAAM,OAAO,KAAK,gBAAgB;KACxD,MAAM;KACN;KACA,UAAU;KACV;KACH,CAAC,CAAC,KAEwC;IAAM;WAE9C,GAAO;AACV,UAAO,EAAoB,EAAM;;;CAUzC,MAAM,UAAU,GAAqD;AACjE,MAAI;AAGA,UAAO;IAAE,SAAS;IAAM,QAFT,MAAM,KAAK,MAAM,UAAa,EAAS;IAEtB;WAE7B,GAAO;AACV,UAAO,EAAgB,EAAM;;;CAYrC,MAAM,SACF,GACA,IAA2B,EAAE,EAC7B,IAA6B,EAAE,EACH;AAC5B,MAAI;AAGA,UAAO;IAAE,SAAS;IAAM,QAFT,MAAM,KAAK,MAAM,SAAS,GAAK,GAAQ,EAAQ;IAE9B;WAE7B,GAAO;AACV,UAAO,EAAsB,EAAM"}
|
|
@@ -17,7 +17,7 @@ export declare class MongoController<D extends Partial<C_Document>> {
|
|
|
17
17
|
* @param db - The MongoDB database instance.
|
|
18
18
|
* @param collectionName - The name of the collection to operate on.
|
|
19
19
|
* @param options - Optional configuration for the controller.
|
|
20
|
-
* @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default:
|
|
20
|
+
* @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 1,000).
|
|
21
21
|
*/
|
|
22
22
|
constructor(db: C_Db, collectionName: string, options?: {
|
|
23
23
|
defaultLimit?: number;
|
|
@@ -7,7 +7,7 @@ var i = class {
|
|
|
7
7
|
defaultLimit;
|
|
8
8
|
collectionName;
|
|
9
9
|
constructor(e, t, n) {
|
|
10
|
-
this.collection = e.collection(t), this.collectionName = t, this.defaultLimit = n?.defaultLimit ??
|
|
10
|
+
this.collection = e.collection(t), this.collectionName = t, this.defaultLimit = n?.defaultLimit ?? 1e3;
|
|
11
11
|
}
|
|
12
12
|
async createOne(n) {
|
|
13
13
|
try {
|
|
@@ -65,11 +65,12 @@ var i = class {
|
|
|
65
65
|
}
|
|
66
66
|
async findAll(e = {}) {
|
|
67
67
|
try {
|
|
68
|
-
let t = await this.collection.find(e).limit(this.defaultLimit).maxTimeMS(3e4).toArray();
|
|
69
|
-
return
|
|
68
|
+
let t = await this.collection.find(e).limit(this.defaultLimit).maxTimeMS(3e4).toArray(), r = t.length === this.defaultLimit;
|
|
69
|
+
return r && n.warn(`[${this.collectionName}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`), {
|
|
70
70
|
success: !0,
|
|
71
71
|
message: "Documents retrieved successfully",
|
|
72
|
-
result: t
|
|
72
|
+
result: t,
|
|
73
|
+
truncated: r
|
|
73
74
|
};
|
|
74
75
|
} catch (e) {
|
|
75
76
|
return t(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongo.controller.native.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.native.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\n\nimport type { C_Collection, C_Db, C_Document, T_DeleteResult, T_Filter, T_OptionalUnlessRequiredId, T_UpdateResult, T_WithId } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { mongo } from './mongo.util.js';\n\n/**\n * MongoDB native driver controller for direct database operations.\n * This class provides a simplified interface for MongoDB operations using the native driver,\n * with automatic generic field generation and standardized response formatting.\n *\n * @see I_MongoController for the shared polymorphic interface (use via type assertion when needed).\n */\nexport class MongoController<D extends Partial<C_Document>> {\n private collection: C_Collection<D>;\n private defaultLimit: number;\n private collectionName: string;\n\n /**\n * Creates a new MongoDB controller instance.\n *\n * @param db - The MongoDB database instance.\n * @param collectionName - The name of the collection to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 10,000).\n */\n constructor(db: C_Db, collectionName: string, options?: { defaultLimit?: number }) {\n this.collection = db.collection<D>(collectionName);\n this.collectionName = collectionName;\n this.defaultLimit = options?.defaultLimit ?? 10_000;\n }\n\n /**\n * Creates a single document in the collection.\n * This method adds generic fields (id, isDel, timestamps) to the document before insertion.\n *\n * @param document - The document to create, with or without generic fields.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>> {\n try {\n const finalDocument = {\n ...mongo.createGenericFields(),\n ...document,\n };\n\n const result = await this.collection.insertOne(finalDocument as unknown as T_OptionalUnlessRequiredId<D>);\n\n if (!result.acknowledged) {\n return {\n success: false,\n message: 'Document creation failed',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Document created successfully',\n result: finalDocument,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)>(error);\n }\n }\n\n /**\n * Creates multiple documents in the collection.\n * This method adds generic fields to each document before bulk insertion.\n *\n * @param documents - An array of documents to create.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>> {\n try {\n const finalDocuments = documents.map(document => ({\n ...mongo.createGenericFields(),\n ...document,\n }));\n\n const result = await this.collection.insertMany(finalDocuments as unknown as T_OptionalUnlessRequiredId<D>[]);\n\n if (result.insertedCount === 0) {\n return {\n success: false,\n message: 'No documents were inserted',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n\n return {\n success: true,\n message: `${result.insertedCount} documents created successfully`,\n result: finalDocuments,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)[]>(error);\n }\n }\n\n /**\n * Finds a single document by filter criteria.\n *\n * @param filter - The filter criteria to find the document.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>> {\n try {\n const result = await this.collection.findOne(filter, { maxTimeMS: 30_000 });\n\n if (!result) {\n return { success: false, message: 'Document not found', code: RESPONSE_STATUS.NOT_FOUND.CODE };\n }\n\n return { success: true, message: 'Document found', result };\n }\n catch (error) {\n return catchError<T_WithId<D>>(error);\n }\n }\n\n /**\n * Finds all documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<T_WithId<D>[]>> {\n try {\n const result = await this.collection.find(filter).limit(this.defaultLimit).maxTimeMS(30_000).toArray();\n\n if (result.length === this.defaultLimit) {\n log.warn(`[${this.collectionName}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return {\n success: true,\n message: 'Documents retrieved successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_WithId<D>[]>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<number>> {\n try {\n const result = await this.collection.countDocuments(filter);\n\n return {\n success: true,\n message: `${result} documents counted successfully`,\n result,\n };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Updates a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply to the document.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateOne(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateOne(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n return {\n success: true,\n message: 'Document updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply to the documents.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateMany(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Documents updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteOne(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteOne(filter);\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n return {\n success: true,\n message: 'Document deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteMany(filter);\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Documents deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n}\n"],"mappings":";;;;AAgBA,IAAa,IAAb,MAA4D;CACxD;CACA;CACA;CAUA,YAAY,GAAU,GAAwB,GAAqC;AAG/E,EAFA,KAAK,aAAa,EAAG,WAAc,EAAe,EAClD,KAAK,iBAAiB,GACtB,KAAK,eAAe,GAAS,gBAAgB;;CAUjD,MAAM,UAAU,GAA6D;AACzE,MAAI;GACA,IAAM,IAAgB;IAClB,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN;AAYD,WAVe,MAAM,KAAK,WAAW,UAAU,EAA0D,EAE7F,eAQL;IACH,SAAS;IACT,SAAS;IACT,QAAQ;IACX,GAXU;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,sBAAsB;IAC/C;WASF,GAAO;AACV,UAAO,EAA6B,EAAM;;;CAWlD,MAAM,WAAW,GAAsE;AACnF,MAAI;GACA,IAAM,IAAiB,EAAU,KAAI,OAAa;IAC9C,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN,EAAE,EAEG,IAAS,MAAM,KAAK,WAAW,WAAW,EAA6D;AAU7G,UARI,EAAO,kBAAkB,IAClB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,sBAAsB;IAC/C,GAGE;IACH,SAAS;IACT,SAAS,GAAG,EAAO,cAAc;IACjC,QAAQ;IACX;WAEE,GAAO;AACV,UAAO,EAA+B,EAAM;;;CAUpD,MAAM,QAAQ,GAAqD;AAC/D,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,QAAQ,GAAQ,EAAE,WAAW,KAAQ,CAAC;AAM3E,UAJK,IAIE;IAAE,SAAS;IAAM,SAAS;IAAkB;IAAQ,GAHhD;IAAE,SAAS;IAAO,SAAS;IAAsB,MAAM,EAAgB,UAAU;IAAM;W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;IACT,MAAM,EAAgB,UAAU;IACnC,GAEE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAUhD,MAAM,WACF,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,WAAW,EAAO;AAUvD,UARI,EAAO,iBAAiB,IACjB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,UAAU;IACnC,GAGE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM"}
|
|
1
|
+
{"version":3,"file":"mongo.controller.native.js","names":[],"sources":["../../../src/node/mongo/mongo.controller.native.ts"],"sourcesContent":["import type { I_Return } from '#typescript/index.js';\n\nimport { RESPONSE_STATUS } from '#constant/index.js';\n\nimport type { C_Collection, C_Db, C_Document, T_DeleteResult, T_Filter, T_OptionalUnlessRequiredId, T_UpdateResult, T_WithId } from './mongo.type.js';\n\nimport { catchError, log } from '../log/index.js';\nimport { mongo } from './mongo.util.js';\n\n/**\n * MongoDB native driver controller for direct database operations.\n * This class provides a simplified interface for MongoDB operations using the native driver,\n * with automatic generic field generation and standardized response formatting.\n *\n * @see I_MongoController for the shared polymorphic interface (use via type assertion when needed).\n */\nexport class MongoController<D extends Partial<C_Document>> {\n private collection: C_Collection<D>;\n private defaultLimit: number;\n private collectionName: string;\n\n /**\n * Creates a new MongoDB controller instance.\n *\n * @param db - The MongoDB database instance.\n * @param collectionName - The name of the collection to operate on.\n * @param options - Optional configuration for the controller.\n * @param options.defaultLimit - Maximum documents returned by findAll when no limit is specified (default: 1,000).\n */\n constructor(db: C_Db, collectionName: string, options?: { defaultLimit?: number }) {\n this.collection = db.collection<D>(collectionName);\n this.collectionName = collectionName;\n this.defaultLimit = options?.defaultLimit ?? 1_000;\n }\n\n /**\n * Creates a single document in the collection.\n * This method adds generic fields (id, isDel, timestamps) to the document before insertion.\n *\n * @param document - The document to create, with or without generic fields.\n * @returns A promise that resolves to a standardized response with the created document.\n */\n async createOne(document: D | Partial<D>): Promise<I_Return<D | Partial<D>>> {\n try {\n const finalDocument = {\n ...mongo.createGenericFields(),\n ...document,\n };\n\n const result = await this.collection.insertOne(finalDocument as unknown as T_OptionalUnlessRequiredId<D>);\n\n if (!result.acknowledged) {\n return {\n success: false,\n message: 'Document creation failed',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Document created successfully',\n result: finalDocument,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)>(error);\n }\n }\n\n /**\n * Creates multiple documents in the collection.\n * This method adds generic fields to each document before bulk insertion.\n *\n * @param documents - An array of documents to create.\n * @returns A promise that resolves to a standardized response with the created documents.\n */\n async createMany(documents: (D | Partial<D>)[]): Promise<I_Return<(D | Partial<D>)[]>> {\n try {\n const finalDocuments = documents.map(document => ({\n ...mongo.createGenericFields(),\n ...document,\n }));\n\n const result = await this.collection.insertMany(finalDocuments as unknown as T_OptionalUnlessRequiredId<D>[]);\n\n if (result.insertedCount === 0) {\n return {\n success: false,\n message: 'No documents were inserted',\n code: RESPONSE_STATUS.INTERNAL_SERVER_ERROR.CODE,\n };\n }\n\n return {\n success: true,\n message: `${result.insertedCount} documents created successfully`,\n result: finalDocuments,\n };\n }\n catch (error) {\n return catchError<(D | Partial<D>)[]>(error);\n }\n }\n\n /**\n * Finds a single document by filter criteria.\n *\n * @param filter - The filter criteria to find the document.\n * @returns A promise that resolves to a standardized response with the found document.\n */\n async findOne(filter: T_Filter<D>): Promise<I_Return<T_WithId<D>>> {\n try {\n const result = await this.collection.findOne(filter, { maxTimeMS: 30_000 });\n\n if (!result) {\n return { success: false, message: 'Document not found', code: RESPONSE_STATUS.NOT_FOUND.CODE };\n }\n\n return { success: true, message: 'Document found', result };\n }\n catch (error) {\n return catchError<T_WithId<D>>(error);\n }\n }\n\n /**\n * Finds all documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the found documents.\n */\n async findAll(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<T_WithId<D>[]>> {\n try {\n const result = await this.collection.find(filter).limit(this.defaultLimit).maxTimeMS(30_000).toArray();\n\n const truncated = result.length === this.defaultLimit;\n\n if (truncated) {\n log.warn(`[${this.collectionName}] findAll returned exactly ${this.defaultLimit} documents (the default limit). Results may be truncated. Consider using pagination or setting an explicit limit.`);\n }\n\n return {\n success: true,\n message: 'Documents retrieved successfully',\n result,\n truncated,\n };\n }\n catch (error) {\n return catchError<T_WithId<D>[]>(error);\n }\n }\n\n /**\n * Counts documents matching the filter criteria.\n *\n * @param filter - The filter criteria to count documents (defaults to empty object for all documents).\n * @returns A promise that resolves to a standardized response with the document count.\n */\n async count(\n filter: T_Filter<D> = {},\n ): Promise<I_Return<number>> {\n try {\n const result = await this.collection.countDocuments(filter);\n\n return {\n success: true,\n message: `${result} documents counted successfully`,\n result,\n };\n }\n catch (error) {\n return catchError<number>(error);\n }\n }\n\n /**\n * Updates a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to update.\n * @param update - The update data to apply to the document.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateOne(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateOne(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n return {\n success: true,\n message: 'Document updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Updates multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to update.\n * @param update - The update data to apply to the documents.\n * @returns A promise that resolves to a standardized response with the update result.\n */\n async updateMany(\n filter: T_Filter<D>,\n update: Partial<D>,\n ): Promise<I_Return<T_UpdateResult>> {\n try {\n const result = await this.collection.updateMany(filter, {\n $set: update,\n });\n\n if (result.matchedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Documents updated successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_UpdateResult>(error);\n }\n }\n\n /**\n * Deletes a single document matching the filter criteria.\n *\n * @param filter - The filter criteria to find the document to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteOne(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteOne(filter);\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n return {\n success: true,\n message: 'Document deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n\n /**\n * Deletes multiple documents matching the filter criteria.\n *\n * @param filter - The filter criteria to find documents to delete.\n * @returns A promise that resolves to a standardized response with the delete result.\n */\n async deleteMany(\n filter: T_Filter<D>,\n ): Promise<I_Return<T_DeleteResult>> {\n try {\n const result = await this.collection.deleteMany(filter);\n\n if (result.deletedCount === 0) {\n return {\n success: false,\n message: 'No documents matched the filter',\n code: RESPONSE_STATUS.NOT_FOUND.CODE,\n };\n }\n\n return {\n success: true,\n message: 'Documents deleted successfully',\n result,\n };\n }\n catch (error) {\n return catchError<T_DeleteResult>(error);\n }\n }\n}\n"],"mappings":";;;;AAgBA,IAAa,IAAb,MAA4D;CACxD;CACA;CACA;CAUA,YAAY,GAAU,GAAwB,GAAqC;AAG/E,EAFA,KAAK,aAAa,EAAG,WAAc,EAAe,EAClD,KAAK,iBAAiB,GACtB,KAAK,eAAe,GAAS,gBAAgB;;CAUjD,MAAM,UAAU,GAA6D;AACzE,MAAI;GACA,IAAM,IAAgB;IAClB,GAAG,EAAM,qBAAqB;IAC9B,GAAG;IACN;AAYD,WAVe,MAAM,KAAK,WAAW,U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O;AAE3D,UAAO;IACH,SAAS;IACT,SAAS,GAAG,EAAO;IACnB;IACH;WAEE,GAAO;AACV,UAAO,EAAmB,EAAM;;;CAWxC,MAAM,UACF,GACA,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,UAAU,GAAQ,EACnD,MAAM,GACT,CAAC;AASF,UAPI,EAAO,iBAAiB,IACjB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,UAAU;IACnC,GAEE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAWhD,MAAM,WACF,GACA,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,WAAW,GAAQ,EACpD,MAAM,GACT,CAAC;AAUF,UARI,EAAO,iBAAiB,IACjB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,UAAU;IACnC,GAGE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAUhD,MAAM,UACF,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,UAAU,EAAO;AAStD,UAPI,EAAO,iBAAiB,IACjB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,UAAU;IACnC,GAEE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM;;;CAUhD,MAAM,WACF,GACiC;AACjC,MAAI;GACA,IAAM,IAAS,MAAM,KAAK,WAAW,WAAW,EAAO;AAUvD,UARI,EAAO,iBAAiB,IACjB;IACH,SAAS;IACT,SAAS;IACT,MAAM,EAAgB,UAAU;IACnC,GAGE;IACH,SAAS;IACT,SAAS;IACT;IACH;WAEE,GAAO;AACV,UAAO,EAA2B,EAAM"}
|
|
@@ -5,6 +5,21 @@ import { T_DeleteResult, T_UpdateResult, T_WithId } from './mongo.type.js';
|
|
|
5
5
|
* Both `MongooseController` and `MongoController` implement this interface,
|
|
6
6
|
* enabling polymorphic usage and dependency injection.
|
|
7
7
|
*
|
|
8
|
+
* ## Choosing a Controller
|
|
9
|
+
* - **`MongooseController`** — Use when you need Mongoose features: schema validation,
|
|
10
|
+
* middleware hooks, virtual fields, population, pagination plugins, or slug generation.
|
|
11
|
+
* - **`MongoController`** — Use for simple CRUD without Mongoose overhead. Ideal for
|
|
12
|
+
* lightweight services, migrations, or seed scripts using the native MongoDB driver.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* ```typescript
|
|
16
|
+
* // Dependency injection using the shared interface
|
|
17
|
+
* class UserService {
|
|
18
|
+
* constructor(private db: I_MongoController<User>) {}
|
|
19
|
+
* async getUser(id: string) { return this.db.findOne({ id }); }
|
|
20
|
+
* }
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
8
23
|
* @template T - The document type for the collection.
|
|
9
24
|
*/
|
|
10
25
|
export interface I_MongoController<T> {
|
|
@@ -69,22 +69,22 @@ async function c(t, n, i, a, c, l) {
|
|
|
69
69
|
return !1;
|
|
70
70
|
});
|
|
71
71
|
if (u.length === 0) return n;
|
|
72
|
-
let d = n.map((e) => s(e) ? e.toObject() : e)
|
|
73
|
-
|
|
72
|
+
let d = e(n.map((e) => s(e) ? e.toObject() : e));
|
|
73
|
+
d.forEach((e) => {
|
|
74
74
|
u.forEach(({ name: t, options: n }) => {
|
|
75
75
|
t in e || (e[t] = n.count ? 0 : n.justOne ? null : []);
|
|
76
76
|
});
|
|
77
77
|
});
|
|
78
|
-
let
|
|
78
|
+
let f = /* @__PURE__ */ new Map();
|
|
79
79
|
for (let e of u) {
|
|
80
|
-
let { name: t, options: n } = e, r = o(
|
|
80
|
+
let { name: t, options: n } = e, r = o(d, t, n);
|
|
81
81
|
for (let i of r) {
|
|
82
|
-
|
|
82
|
+
f.has(i.model) || f.set(i.model, {
|
|
83
83
|
virtuals: [],
|
|
84
84
|
localValueSets: /* @__PURE__ */ new Map(),
|
|
85
85
|
docsByLocalValue: /* @__PURE__ */ new Map()
|
|
86
86
|
});
|
|
87
|
-
let r =
|
|
87
|
+
let r = f.get(i.model);
|
|
88
88
|
r.virtuals.some((e) => e.name === t) || (r.virtuals.push(e), r.localValueSets.set(t, /* @__PURE__ */ new Set()));
|
|
89
89
|
let a = r.localValueSets.get(t);
|
|
90
90
|
i.docs.forEach((e) => {
|
|
@@ -93,12 +93,12 @@ async function c(t, n, i, a, c, l) {
|
|
|
93
93
|
let n = String(t);
|
|
94
94
|
a.add(n);
|
|
95
95
|
let i = -1, o = e;
|
|
96
|
-
o.id === void 0 ? o._id !== void 0 && (i =
|
|
96
|
+
o.id === void 0 ? o._id !== void 0 && (i = d.findIndex((e) => e._id?.toString?.() === o._id?.toString?.())) : i = d.findIndex((e) => e.id === o.id), i !== -1 && (r.docsByLocalValue.has(n) || r.docsByLocalValue.set(n, []), r.docsByLocalValue.get(n).push(i));
|
|
97
97
|
}
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
100
|
}
|
|
101
|
-
return await Promise.all(Array.from(
|
|
101
|
+
return await Promise.all(Array.from(f.entries(), async ([e, n]) => {
|
|
102
102
|
let r = t.models[e];
|
|
103
103
|
if (!r) return;
|
|
104
104
|
let i = /* @__PURE__ */ new Set();
|
|
@@ -121,7 +121,7 @@ async function c(t, n, i, a, c, l) {
|
|
|
121
121
|
}), n.localValueSets.get(t).forEach((r) => {
|
|
122
122
|
let i = n.docsByLocalValue.get(r) || [], a = e.get(r) || 0;
|
|
123
123
|
i.forEach((e) => {
|
|
124
|
-
let n =
|
|
124
|
+
let n = d[e];
|
|
125
125
|
n[t] === void 0 && (n[t] = a);
|
|
126
126
|
});
|
|
127
127
|
});
|
|
@@ -133,13 +133,13 @@ async function c(t, n, i, a, c, l) {
|
|
|
133
133
|
}), n.localValueSets.get(t).forEach((i) => {
|
|
134
134
|
let a = n.docsByLocalValue.get(i) || [], o = e.get(i) || [], s = r.justOne ? o[0] || null : o;
|
|
135
135
|
a.forEach((e) => {
|
|
136
|
-
let n =
|
|
136
|
+
let n = d[e];
|
|
137
137
|
n[t] = s;
|
|
138
138
|
});
|
|
139
139
|
});
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
-
})), a && await r(t,
|
|
142
|
+
})), a && await r(t, d, ((e) => {
|
|
143
143
|
let t = Array.isArray(e) ? e : [e], n = /* @__PURE__ */ new Map(), r = [];
|
|
144
144
|
for (let e of t) if (typeof e == "string") if (e.includes(".")) {
|
|
145
145
|
let t = e.split("."), r = t[0] || "", i = t.slice(1).join(".");
|
|
@@ -161,7 +161,7 @@ async function c(t, n, i, a, c, l) {
|
|
|
161
161
|
populate: n
|
|
162
162
|
} : t);
|
|
163
163
|
}), i;
|
|
164
|
-
})(a), i, l),
|
|
164
|
+
})(a), i, l), d;
|
|
165
165
|
}
|
|
166
166
|
//#endregion
|
|
167
167
|
export { a as filterDynamicVirtualsFromPopulate, s as isMongooseDoc, i as isObject, c as populateDynamicVirtuals, o as remapDynamicPopulate };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongo.dynamic-populate.js","names":[],"sources":["../../../src/node/mongo/mongo.dynamic-populate.ts"],"sourcesContent":["import type mongooseRaw from 'mongoose';\n\nimport { deepClone } from '#util/index.js';\n\nimport type { I_ModelWithSchema } from './mongo.internal-types.js';\nimport type { I_DynamicVirtualConfig, I_DynamicVirtualOptions, T_Input_Populate } from './mongo.type.js';\n\nimport { catchError } from '../log/index.js';\nimport { applyNestedPopulate } from './mongo.populate.js';\nimport { convertEnumToModelName } from './mongo.util.js';\n\n/**\n * Checks if value is object-like (e.g., objects, arrays, etc.), not null.\n */\nexport function isObject(value: unknown): value is object {\n return value != null && typeof value === 'object';\n}\n\n/**\n * Filters out dynamic virtuals from populate options to prevent Mongoose from trying to populate them.\n * This function creates a new populate configuration that only includes regular virtuals.\n *\n * @template T - The document type\n * @param populate - The original populate options\n * @param dynamicVirtuals - Array of dynamic virtual configurations\n * @returns Filtered populate options excluding dynamic virtuals\n */\nexport function filterDynamicVirtualsFromPopulate<T>(\n populate: T_Input_Populate | undefined,\n dynamicVirtuals: I_DynamicVirtualConfig<T>[] | undefined,\n): T_Input_Populate | undefined {\n if (!populate || !dynamicVirtuals || dynamicVirtuals.length === 0) {\n return populate;\n }\n\n const dynamicVirtualNames = new Set(dynamicVirtuals.map(v => v.name));\n\n if (Array.isArray(populate)) {\n const filtered = populate.filter((p) => {\n if (typeof p === 'string') {\n return ![...dynamicVirtualNames].some(virtualName =>\n p === virtualName || p.startsWith(`${virtualName}.`),\n );\n }\n\n if (typeof p === 'object' && p !== null) {\n const popObj = p as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return ![...dynamicVirtualNames].some(virtualName =>\n path === virtualName || path.startsWith(`${virtualName}.`),\n );\n }\n\n return true;\n });\n\n return filtered.length > 0 ? (filtered as T_Input_Populate) : undefined;\n }\n\n if (typeof populate === 'string') {\n return [...dynamicVirtualNames].some(virtualName =>\n populate === virtualName || populate.startsWith(`${virtualName}.`),\n )\n ? undefined\n : populate;\n }\n\n if (typeof populate === 'object' && populate !== null) {\n const popObj = populate as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return [...dynamicVirtualNames].some(virtualName =>\n path === virtualName || path.startsWith(`${virtualName}.`),\n )\n ? undefined\n : populate;\n }\n\n return populate;\n}\n\n/**\n * Groups documents by the resolved model name for a dynamic virtual field.\n * Used to batch population queries for dynamic virtuals.\n *\n * @template T - The document type\n * @template R - The model name type (usually string or enum)\n * @param {T[]} documents - The array of documents to process\n * @param {string} virtualName - The name of the dynamic virtual field\n * @param {I_DynamicVirtualOptions<T, R>} virtualOptions - The dynamic virtual options (must include a ref function)\n * @returns {Array<{ model: string; docs: T[] }>} An array of groups, each with a model name and the docs for that model\n */\nexport function remapDynamicPopulate<T, R extends string = string>(\n documents: T[],\n virtualName: string,\n virtualOptions: I_DynamicVirtualOptions<T, R>,\n): Array<{ model: string; docs: T[] }> {\n if (!documents.length || !virtualName || !virtualOptions?.ref) {\n return [];\n }\n\n const modelGroups = new Map<string, T[]>();\n documents.forEach((doc) => {\n try {\n const modelName = virtualOptions.ref(doc);\n\n if (modelName === undefined || modelName === null) {\n return;\n }\n\n const modelNameString = typeof modelName === 'string' ? modelName : String(modelName);\n\n if (modelNameString && modelNameString.trim() !== '') {\n const convertedModelName = convertEnumToModelName(modelNameString);\n\n if (!modelGroups.has(convertedModelName)) {\n modelGroups.set(convertedModelName, []);\n }\n\n modelGroups.get(convertedModelName)!.push(doc);\n }\n }\n catch (error) {\n catchError(new Error(`Dynamic ref function failed for virtual \"${virtualName}\": ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n\n return Array.from(modelGroups.entries(), ([model, docs]) => ({ model, docs }));\n}\n\n/**\n * Type guard to check if an object is a Mongoose Document (has toObject method).\n * @param obj - The object to check\n * @returns True if obj has a toObject function\n */\nexport function isMongooseDoc(obj: unknown): obj is { toObject: () => { [key: string]: unknown } } {\n return obj !== null && typeof obj === 'object' && 'toObject' in obj && typeof (obj as { toObject: unknown }).toObject === 'function';\n}\n\n/**\n * Optimized batch population for dynamic virtuals.\n *\n * - Groups documents by model and batches queries for each model.\n * - Populates all dynamic virtuals in parallel for maximum performance.\n * - Uses direct assignment for plain objects and skips already populated fields.\n * - Supports optional projection for population queries.\n * - Only populates virtuals that are explicitly requested in populate options.\n * - Reminder: Ensure indexes exist on foreignField in referenced collections for best performance.\n *\n * @template T - The document type (must be an object)\n * @template R - The model name type (usually string or enum)\n * @param {typeof mongooseRaw} mongoose - The Mongoose instance\n * @param {T[]} documents - The array of documents to populate\n * @param {I_DynamicVirtualConfig<T, R>[]} virtualConfigs - The dynamic virtual configurations to process\n * @param {T_Input_Populate} [populate] - Population options to determine which virtuals to populate\n * @param {Record<string, 0 | 1>} [projection] - Optional projection for population queries\n * @returns {Promise<object[]>} The array of documents with dynamic virtuals populated\n */\nexport async function populateDynamicVirtuals<T extends object, R extends string = string>(\n mongoose: typeof mongooseRaw,\n documents: T[],\n virtualConfigs: I_DynamicVirtualConfig<T, R>[],\n populate?: T_Input_Populate,\n projection?: Record<string, 0 | 1>,\n startModel?: I_ModelWithSchema,\n): Promise<T[]> {\n if (!documents.length || !virtualConfigs.length) {\n return documents;\n }\n\n if (!populate) {\n return documents;\n }\n\n const requestedVirtuals = virtualConfigs.filter((config) => {\n if (Array.isArray(populate)) {\n return populate.length > 0 && populate.some((p) => {\n if (typeof p === 'string') {\n return p === config.name || p.startsWith(`${config.name}.`);\n }\n if (p && typeof p === 'object') {\n const popObj = p as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return path === config.name || path.startsWith(`${config.name}.`);\n }\n\n return false;\n });\n }\n\n if (typeof populate === 'string') {\n return populate === config.name || populate.startsWith(`${config.name}.`);\n }\n\n if (typeof populate === 'object' && populate !== null) {\n const popObj = populate as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return (path === config.name) || path.startsWith(`${config.name}.`);\n }\n\n return false;\n });\n\n if (requestedVirtuals.length === 0) {\n return documents;\n }\n\n // Only deepClone documents that need it. toObject() already creates a plain copy,\n // so we avoid redundant deep cloning for Mongoose documents.\n const plainDocuments = documents.map(doc => isMongooseDoc(doc) ? doc.toObject() : doc);\n const clonedDocuments = plainDocuments.some(doc => isMongooseDoc(doc)) ? plainDocuments as T[] : deepClone(plainDocuments) as T[];\n\n clonedDocuments.forEach((doc) => {\n requestedVirtuals.forEach(({ name, options }) => {\n if (!(name in doc)) {\n (doc as { [key: string]: unknown })[name as string] = options.count ? 0 : (options.justOne ? null : []);\n }\n });\n });\n\n const modelProcessingMap = new Map<string, {\n virtuals: I_DynamicVirtualConfig<T, R>[];\n localValueSets: Map<string, Set<string>>;\n docsByLocalValue: Map<string, number[]>;\n }>();\n\n for (const virtualConfig of requestedVirtuals) {\n const { name, options } = virtualConfig;\n const populateGroups = remapDynamicPopulate(clonedDocuments, name, options);\n\n for (const group of populateGroups) {\n if (!modelProcessingMap.has(group.model)) {\n modelProcessingMap.set(group.model, {\n virtuals: [],\n localValueSets: new Map(),\n docsByLocalValue: new Map(),\n });\n }\n\n const processing = modelProcessingMap.get(group.model)!;\n\n if (!processing.virtuals.some(v => v.name === name)) {\n processing.virtuals.push(virtualConfig);\n processing.localValueSets.set(name as string, new Set());\n }\n\n const localValueSet = processing.localValueSets.get(name as string)!;\n group.docs.forEach((doc) => {\n const localVal = (doc as { [key: string]: unknown })[options.localField];\n\n if (localVal != null) {\n const strVal = String(localVal);\n localValueSet.add(strVal);\n\n let idx = -1;\n\n const docWithKeys = doc as { [key: string]: unknown };\n\n if (docWithKeys['id'] !== undefined) {\n idx = clonedDocuments.findIndex((d) => {\n const dWithKeys = d as { [key: string]: unknown };\n\n return dWithKeys['id'] === docWithKeys['id'];\n });\n }\n else if (docWithKeys['_id'] !== undefined) {\n idx = clonedDocuments.findIndex((d) => {\n const dWithKeys = d as { [key: string]: unknown };\n\n return dWithKeys['_id']?.toString?.() === docWithKeys['_id']?.toString?.();\n });\n }\n\n if (idx !== -1) {\n if (!processing.docsByLocalValue.has(strVal)) {\n processing.docsByLocalValue.set(strVal, []);\n }\n processing.docsByLocalValue.get(strVal)!.push(idx);\n }\n }\n });\n }\n }\n\n await Promise.all(Array.from(modelProcessingMap.entries(), async ([modelName, processing]) => {\n const Model = mongoose.models[modelName];\n\n if (!Model) {\n return;\n }\n\n const allLocalValues = new Set<string>();\n processing.localValueSets.forEach((localValueSet) => {\n localValueSet.forEach(val => allLocalValues.add(val));\n });\n\n if (allLocalValues.size === 0) {\n return;\n }\n\n const foreignFields = [...new Set(processing.virtuals.map(v => v.options.foreignField))];\n const localValuesArray = [...allLocalValues];\n let query;\n\n if (foreignFields.length === 1) {\n query = { [String(foreignFields[0])]: { $in: localValuesArray } };\n }\n else {\n query = { $or: foreignFields.map(field => ({ [field]: { $in: localValuesArray } })) };\n }\n\n const allPopulatedData = await Model.find(query, projection).lean();\n\n for (const virtualConfig of processing.virtuals) {\n const { name, options } = virtualConfig;\n const relevantData = allPopulatedData.filter((item) => {\n const foreignVal = (item)[options.foreignField];\n\n return foreignVal != null && allLocalValues.has(String(foreignVal));\n });\n\n if (options.count) {\n const countMap = new Map<string, number>();\n\n relevantData.forEach((item) => {\n const key = (item)[options.foreignField]?.toString();\n\n if (key) {\n countMap.set(key, (countMap.get(key) || 0) + 1);\n }\n });\n\n processing.localValueSets.get(name as string)!.forEach((localValue) => {\n const docs = processing.docsByLocalValue.get(localValue) || [];\n const count = countMap.get(localValue) || 0;\n\n docs.forEach((idx) => {\n const docToUpdate = clonedDocuments[idx] as { [key: string]: unknown };\n\n if (docToUpdate[name] === undefined) {\n docToUpdate[name] = count;\n }\n });\n });\n }\n else {\n const resultMap = new Map<string, T[]>();\n\n relevantData.forEach((item) => {\n const key = (item)[options.foreignField]?.toString();\n\n if (key) {\n if (!resultMap.has(key)) {\n resultMap.set(key, []);\n }\n resultMap.get(key)!.push(item);\n }\n });\n\n processing.localValueSets.get(name as string)!.forEach((localVal) => {\n const docs = processing.docsByLocalValue.get(localVal) || [];\n const results = resultMap.get(localVal) || [];\n const value = options.justOne ? (results[0] || null) : results;\n\n docs.forEach((idx) => {\n const docToUpdate = clonedDocuments[idx] as { [key: string]: unknown };\n docToUpdate[name] = value;\n });\n });\n }\n }\n }));\n\n if (populate) {\n const normalizePopulate = (pop: T_Input_Populate): T_Input_Populate => {\n const asArray = Array.isArray(pop) ? pop : [pop];\n const grouped = new Map<string, unknown[]>();\n const passthrough: unknown[] = [];\n\n for (const entry of asArray) {\n if (typeof entry === 'string') {\n if (entry.includes('.')) {\n const parts = entry.split('.');\n const first = parts[0] || '';\n const rest = parts.slice(1).join('.');\n\n if (first) {\n if (!grouped.has(first)) {\n grouped.set(first, []);\n }\n if (rest) {\n grouped.get(first)!.push(rest);\n }\n }\n }\n else {\n passthrough.push(entry);\n }\n }\n else if (entry && typeof entry === 'object') {\n const obj = entry as { path?: string; populate?: T_Input_Populate };\n\n if (obj.path && obj.path.includes('.')) {\n const parts = obj.path.split('.');\n const first = parts[0] || '';\n const rest = parts.slice(1).join('.');\n\n if (first) {\n if (!grouped.has(first)) {\n grouped.set(first, []);\n }\n if (rest) {\n grouped.get(first)!.push(rest);\n }\n if (obj.populate) {\n grouped.get(first)!.push(obj.populate);\n }\n }\n }\n else {\n passthrough.push(entry);\n }\n }\n }\n\n const normalized: unknown[] = [...passthrough];\n grouped.forEach((nested, root) => {\n const flat: unknown[] = [];\n\n for (const n of nested) {\n if (typeof n === 'string') {\n flat.push(n);\n }\n else if (n && typeof n === 'object') {\n flat.push(n);\n }\n }\n if (flat.length > 0) {\n normalized.push({ path: root, populate: flat as unknown as T_Input_Populate });\n }\n else {\n normalized.push(root);\n }\n });\n\n return normalized as unknown as T_Input_Populate;\n };\n\n const normalizedPopulate = normalizePopulate(populate);\n\n await applyNestedPopulate(mongoose, clonedDocuments, normalizedPopulate, virtualConfigs as I_DynamicVirtualConfig<unknown, string>[], startModel);\n }\n\n return clonedDocuments;\n}\n"],"mappings":";;;;;AAcA,SAAgB,EAAS,GAAiC;AACtD,QAAwB,OAAO,KAAU,cAAlC;;AAYX,SAAgB,EACZ,GACA,GAC4B;AAC5B,KAAI,CAAC,KAAY,CAAC,KAAmB,EAAgB,WAAW,EAC5D,QAAO;CAGX,IAAM,IAAsB,IAAI,IAAI,EAAgB,KAAI,MAAK,EAAE,KAAK,CAAC;AAErE,KAAI,MAAM,QAAQ,EAAS,EAAE;EACzB,IAAM,IAAW,EAAS,QAAQ,MAAM;AACpC,OAAI,OAAO,KAAM,SACb,QAAO,CAAC,CAAC,GAAG,EAAoB,CAAC,MAAK,MAClC,MAAM,KAAe,EAAE,WAAW,GAAG,EAAY,GAAG,CACvD;AAGL,OAAI,OAAO,KAAM,YAAY,GAAY;IACrC,IAAM,IAAS,GACT,IAAO,EAAO,QAAQ,EAAO,YAAY;AAE/C,WAAO,CAAC,CAAC,GAAG,EAAoB,CAAC,MAAK,MAClC,MAAS,KAAe,EAAK,WAAW,GAAG,EAAY,GAAG,CAC7D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J,EAAQ,IAAI,EAAM,CAAE,KAAK,EAAI,SAAS;SAK9C,GAAY,KAAK,EAAM;;EAKnC,IAAM,IAAwB,CAAC,GAAG,EAAY;AAoB9C,SAnBA,EAAQ,SAAS,GAAQ,MAAS;GAC9B,IAAM,IAAkB,EAAE;AAE1B,QAAK,IAAM,KAAK,EACZ,EAAI,OAAO,KAAM,YAGR,KAAK,OAAO,KAAM,aAFvB,EAAK,KAAK,EAAE;AAMpB,GACI,EAAW,KADX,EAAK,SAAS,IACE;IAAE,MAAM;IAAM,UAAU;IAAqC,GAG7D,EAAK;IAE3B,EAEK;IAGkC,EAAS,EAEmB,GAA6D,EAAW,EAG9I"}
|
|
1
|
+
{"version":3,"file":"mongo.dynamic-populate.js","names":[],"sources":["../../../src/node/mongo/mongo.dynamic-populate.ts"],"sourcesContent":["import type mongooseRaw from 'mongoose';\n\nimport { deepClone } from '#util/index.js';\n\nimport type { I_ModelWithSchema } from './mongo.internal-types.js';\nimport type { I_DynamicVirtualConfig, I_DynamicVirtualOptions, T_Input_Populate } from './mongo.type.js';\n\nimport { catchError } from '../log/index.js';\nimport { applyNestedPopulate } from './mongo.populate.js';\nimport { convertEnumToModelName } from './mongo.util.js';\n\n/**\n * Checks if value is object-like (e.g., objects, arrays, etc.), not null.\n */\nexport function isObject(value: unknown): value is object {\n return value != null && typeof value === 'object';\n}\n\n/**\n * Filters out dynamic virtuals from populate options to prevent Mongoose from trying to populate them.\n * This function creates a new populate configuration that only includes regular virtuals.\n *\n * @template T - The document type\n * @param populate - The original populate options\n * @param dynamicVirtuals - Array of dynamic virtual configurations\n * @returns Filtered populate options excluding dynamic virtuals\n */\nexport function filterDynamicVirtualsFromPopulate<T>(\n populate: T_Input_Populate | undefined,\n dynamicVirtuals: I_DynamicVirtualConfig<T>[] | undefined,\n): T_Input_Populate | undefined {\n if (!populate || !dynamicVirtuals || dynamicVirtuals.length === 0) {\n return populate;\n }\n\n const dynamicVirtualNames = new Set(dynamicVirtuals.map(v => v.name));\n\n if (Array.isArray(populate)) {\n const filtered = populate.filter((p) => {\n if (typeof p === 'string') {\n return ![...dynamicVirtualNames].some(virtualName =>\n p === virtualName || p.startsWith(`${virtualName}.`),\n );\n }\n\n if (typeof p === 'object' && p !== null) {\n const popObj = p as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return ![...dynamicVirtualNames].some(virtualName =>\n path === virtualName || path.startsWith(`${virtualName}.`),\n );\n }\n\n return true;\n });\n\n return filtered.length > 0 ? (filtered as T_Input_Populate) : undefined;\n }\n\n if (typeof populate === 'string') {\n return [...dynamicVirtualNames].some(virtualName =>\n populate === virtualName || populate.startsWith(`${virtualName}.`),\n )\n ? undefined\n : populate;\n }\n\n if (typeof populate === 'object' && populate !== null) {\n const popObj = populate as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return [...dynamicVirtualNames].some(virtualName =>\n path === virtualName || path.startsWith(`${virtualName}.`),\n )\n ? undefined\n : populate;\n }\n\n return populate;\n}\n\n/**\n * Groups documents by the resolved model name for a dynamic virtual field.\n * Used to batch population queries for dynamic virtuals.\n *\n * @template T - The document type\n * @template R - The model name type (usually string or enum)\n * @param {T[]} documents - The array of documents to process\n * @param {string} virtualName - The name of the dynamic virtual field\n * @param {I_DynamicVirtualOptions<T, R>} virtualOptions - The dynamic virtual options (must include a ref function)\n * @returns {Array<{ model: string; docs: T[] }>} An array of groups, each with a model name and the docs for that model\n */\nexport function remapDynamicPopulate<T, R extends string = string>(\n documents: T[],\n virtualName: string,\n virtualOptions: I_DynamicVirtualOptions<T, R>,\n): Array<{ model: string; docs: T[] }> {\n if (!documents.length || !virtualName || !virtualOptions?.ref) {\n return [];\n }\n\n const modelGroups = new Map<string, T[]>();\n documents.forEach((doc) => {\n try {\n const modelName = virtualOptions.ref(doc);\n\n if (modelName === undefined || modelName === null) {\n return;\n }\n\n const modelNameString = typeof modelName === 'string' ? modelName : String(modelName);\n\n if (modelNameString && modelNameString.trim() !== '') {\n const convertedModelName = convertEnumToModelName(modelNameString);\n\n if (!modelGroups.has(convertedModelName)) {\n modelGroups.set(convertedModelName, []);\n }\n\n modelGroups.get(convertedModelName)!.push(doc);\n }\n }\n catch (error) {\n catchError(new Error(`Dynamic ref function failed for virtual \"${virtualName}\": ${error instanceof Error ? error.message : String(error)}`));\n }\n });\n\n return Array.from(modelGroups.entries(), ([model, docs]) => ({ model, docs }));\n}\n\n/**\n * Type guard to check if an object is a Mongoose Document (has toObject method).\n * @param obj - The object to check\n * @returns True if obj has a toObject function\n */\nexport function isMongooseDoc(obj: unknown): obj is { toObject: () => { [key: string]: unknown } } {\n return obj !== null && typeof obj === 'object' && 'toObject' in obj && typeof (obj as { toObject: unknown }).toObject === 'function';\n}\n\n/**\n * Optimized batch population for dynamic virtuals.\n *\n * - Groups documents by model and batches queries for each model.\n * - Populates all dynamic virtuals in parallel for maximum performance.\n * - Uses direct assignment for plain objects and skips already populated fields.\n * - Supports optional projection for population queries.\n * - Only populates virtuals that are explicitly requested in populate options.\n * - Reminder: Ensure indexes exist on foreignField in referenced collections for best performance.\n *\n * @template T - The document type (must be an object)\n * @template R - The model name type (usually string or enum)\n * @param {typeof mongooseRaw} mongoose - The Mongoose instance\n * @param {T[]} documents - The array of documents to populate\n * @param {I_DynamicVirtualConfig<T, R>[]} virtualConfigs - The dynamic virtual configurations to process\n * @param {T_Input_Populate} [populate] - Population options to determine which virtuals to populate\n * @param {Record<string, 0 | 1>} [projection] - Optional projection for population queries\n * @returns {Promise<object[]>} The array of documents with dynamic virtuals populated\n */\nexport async function populateDynamicVirtuals<T extends object, R extends string = string>(\n mongoose: typeof mongooseRaw,\n documents: T[],\n virtualConfigs: I_DynamicVirtualConfig<T, R>[],\n populate?: T_Input_Populate,\n projection?: Record<string, 0 | 1>,\n startModel?: I_ModelWithSchema,\n): Promise<T[]> {\n if (!documents.length || !virtualConfigs.length) {\n return documents;\n }\n\n if (!populate) {\n return documents;\n }\n\n const requestedVirtuals = virtualConfigs.filter((config) => {\n if (Array.isArray(populate)) {\n return populate.length > 0 && populate.some((p) => {\n if (typeof p === 'string') {\n return p === config.name || p.startsWith(`${config.name}.`);\n }\n if (p && typeof p === 'object') {\n const popObj = p as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return path === config.name || path.startsWith(`${config.name}.`);\n }\n\n return false;\n });\n }\n\n if (typeof populate === 'string') {\n return populate === config.name || populate.startsWith(`${config.name}.`);\n }\n\n if (typeof populate === 'object' && populate !== null) {\n const popObj = populate as { path?: string; populate?: string };\n const path = popObj.path || popObj.populate || '';\n\n return (path === config.name) || path.startsWith(`${config.name}.`);\n }\n\n return false;\n });\n\n if (requestedVirtuals.length === 0) {\n return documents;\n }\n\n // toObject() already creates plain copies for Mongoose docs; deepClone the\n // plain array to avoid mutating the caller's objects.\n const plainDocuments = documents.map(doc => isMongooseDoc(doc) ? doc.toObject() : doc);\n const clonedDocuments = deepClone(plainDocuments) as T[];\n\n clonedDocuments.forEach((doc) => {\n requestedVirtuals.forEach(({ name, options }) => {\n if (!(name in doc)) {\n (doc as { [key: string]: unknown })[name as string] = options.count ? 0 : (options.justOne ? null : []);\n }\n });\n });\n\n const modelProcessingMap = new Map<string, {\n virtuals: I_DynamicVirtualConfig<T, R>[];\n localValueSets: Map<string, Set<string>>;\n docsByLocalValue: Map<string, number[]>;\n }>();\n\n for (const virtualConfig of requestedVirtuals) {\n const { name, options } = virtualConfig;\n const populateGroups = remapDynamicPopulate(clonedDocuments, name, options);\n\n for (const group of populateGroups) {\n if (!modelProcessingMap.has(group.model)) {\n modelProcessingMap.set(group.model, {\n virtuals: [],\n localValueSets: new Map(),\n docsByLocalValue: new Map(),\n });\n }\n\n const processing = modelProcessingMap.get(group.model)!;\n\n if (!processing.virtuals.some(v => v.name === name)) {\n processing.virtuals.push(virtualConfig);\n processing.localValueSets.set(name as string, new Set());\n }\n\n const localValueSet = processing.localValueSets.get(name as string)!;\n group.docs.forEach((doc) => {\n const localVal = (doc as { [key: string]: unknown })[options.localField];\n\n if (localVal != null) {\n const strVal = String(localVal);\n localValueSet.add(strVal);\n\n let idx = -1;\n\n const docWithKeys = doc as { [key: string]: unknown };\n\n if (docWithKeys['id'] !== undefined) {\n idx = clonedDocuments.findIndex((d) => {\n const dWithKeys = d as { [key: string]: unknown };\n\n return dWithKeys['id'] === docWithKeys['id'];\n });\n }\n else if (docWithKeys['_id'] !== undefined) {\n idx = clonedDocuments.findIndex((d) => {\n const dWithKeys = d as { [key: string]: unknown };\n\n return dWithKeys['_id']?.toString?.() === docWithKeys['_id']?.toString?.();\n });\n }\n\n if (idx !== -1) {\n if (!processing.docsByLocalValue.has(strVal)) {\n processing.docsByLocalValue.set(strVal, []);\n }\n processing.docsByLocalValue.get(strVal)!.push(idx);\n }\n }\n });\n }\n }\n\n await Promise.all(Array.from(modelProcessingMap.entries(), async ([modelName, processing]) => {\n const Model = mongoose.models[modelName];\n\n if (!Model) {\n return;\n }\n\n const allLocalValues = new Set<string>();\n processing.localValueSets.forEach((localValueSet) => {\n localValueSet.forEach(val => allLocalValues.add(val));\n });\n\n if (allLocalValues.size === 0) {\n return;\n }\n\n const foreignFields = [...new Set(processing.virtuals.map(v => v.options.foreignField))];\n const localValuesArray = [...allLocalValues];\n let query;\n\n if (foreignFields.length === 1) {\n query = { [String(foreignFields[0])]: { $in: localValuesArray } };\n }\n else {\n query = { $or: foreignFields.map(field => ({ [field]: { $in: localValuesArray } })) };\n }\n\n const allPopulatedData = await Model.find(query, projection).lean();\n\n for (const virtualConfig of processing.virtuals) {\n const { name, options } = virtualConfig;\n const relevantData = allPopulatedData.filter((item) => {\n const foreignVal = (item)[options.foreignField];\n\n return foreignVal != null && allLocalValues.has(String(foreignVal));\n });\n\n if (options.count) {\n const countMap = new Map<string, number>();\n\n relevantData.forEach((item) => {\n const key = (item)[options.foreignField]?.toString();\n\n if (key) {\n countMap.set(key, (countMap.get(key) || 0) + 1);\n }\n });\n\n processing.localValueSets.get(name as string)!.forEach((localValue) => {\n const docs = processing.docsByLocalValue.get(localValue) || [];\n const count = countMap.get(localValue) || 0;\n\n docs.forEach((idx) => {\n const docToUpdate = clonedDocuments[idx] as { [key: string]: unknown };\n\n if (docToUpdate[name] === undefined) {\n docToUpdate[name] = count;\n }\n });\n });\n }\n else {\n const resultMap = new Map<string, T[]>();\n\n relevantData.forEach((item) => {\n const key = (item)[options.foreignField]?.toString();\n\n if (key) {\n if (!resultMap.has(key)) {\n resultMap.set(key, []);\n }\n resultMap.get(key)!.push(item);\n }\n });\n\n processing.localValueSets.get(name as string)!.forEach((localVal) => {\n const docs = processing.docsByLocalValue.get(localVal) || [];\n const results = resultMap.get(localVal) || [];\n const value = options.justOne ? (results[0] || null) : results;\n\n docs.forEach((idx) => {\n const docToUpdate = clonedDocuments[idx] as { [key: string]: unknown };\n docToUpdate[name] = value;\n });\n });\n }\n }\n }));\n\n if (populate) {\n const normalizePopulate = (pop: T_Input_Populate): T_Input_Populate => {\n const asArray = Array.isArray(pop) ? pop : [pop];\n const grouped = new Map<string, unknown[]>();\n const passthrough: unknown[] = [];\n\n for (const entry of asArray) {\n if (typeof entry === 'string') {\n if (entry.includes('.')) {\n const parts = entry.split('.');\n const first = parts[0] || '';\n const rest = parts.slice(1).join('.');\n\n if (first) {\n if (!grouped.has(first)) {\n grouped.set(first, []);\n }\n if (rest) {\n grouped.get(first)!.push(rest);\n }\n }\n }\n else {\n passthrough.push(entry);\n }\n }\n else if (entry && typeof entry === 'object') {\n const obj = entry as { path?: string; populate?: T_Input_Populate };\n\n if (obj.path && obj.path.includes('.')) {\n const parts = obj.path.split('.');\n const first = parts[0] || '';\n const rest = parts.slice(1).join('.');\n\n if (first) {\n if (!grouped.has(first)) {\n grouped.set(first, []);\n }\n if (rest) {\n grouped.get(first)!.push(rest);\n }\n if (obj.populate) {\n grouped.get(first)!.push(obj.populate);\n }\n }\n }\n else {\n passthrough.push(entry);\n }\n }\n }\n\n const normalized: unknown[] = [...passthrough];\n grouped.forEach((nested, root) => {\n const flat: unknown[] = [];\n\n for (const n of nested) {\n if (typeof n === 'string') {\n flat.push(n);\n }\n else if (n && typeof n === 'object') {\n flat.push(n);\n }\n }\n if (flat.length > 0) {\n normalized.push({ path: root, populate: flat as unknown as T_Input_Populate });\n }\n else {\n normalized.push(root);\n }\n });\n\n return normalized as unknown as T_Input_Populate;\n };\n\n const normalizedPopulate = normalizePopulate(populate);\n\n await applyNestedPopulate(mongoose, clonedDocuments, normalizedPopulate, virtualConfigs as I_DynamicVirtualConfig<unknown, string>[], startModel);\n }\n\n return clonedDocuments;\n}\n"],"mappings":";;;;;AAcA,SAAgB,EAAS,GAAiC;AACtD,QAAwB,OAAO,KAAU,cAAlC;;AAYX,SAAgB,EACZ,GACA,GAC4B;AAC5B,KAAI,CAAC,KAAY,CAAC,KAAmB,EAAgB,WAAW,EAC5D,QAAO;CAGX,IAAM,IAAsB,IAAI,IAAI,EAAgB,KAAI,MAAK,EAAE,KAAK,CAAC;AAErE,KAAI,MAAM,QAAQ,EAAS,EAAE;EACzB,IAAM,IAAW,EAAS,QAAQ,MAAM;AACpC,OAAI,OAAO,KAAM,SACb,QAAO,CAAC,CAAC,GAAG,EAAoB,CAAC,MAAK,MAClC,MAAM,KAAe,EAAE,WAAW,GAAG,EAAY,GAAG,CACvD;AAGL,OAAI,OAAO,KAAM,YAAY,GAAY;IACrC,IAAM,IAAS,GACT,IAAO,EAAO,QAAQ,EAAO,YAAY;AAE/C,WAAO,CAAC,CAAC,GAAG,EAAoB,CAAC,MAAK,MAClC,MAAS,KAAe,EAAK,WAAW,GAAG,EAAY,GAAG,CAC7D;;AAGL,UAAO;IACT;AAEF,SAAO,EAAS,SAAS,IAAK,IAAgC,KAAA;;AAGlE,KAAI,OAAO,KAAa,SACpB,QAAO,CAAC,GAAG,EAAoB,CAAC,MAAK,MACjC,MAAa,KAAe,EAAS,WAAW,GAAG,EAAY,GAAG,CACrE,GACK,KAAA,IACA;AAGV,KAAI,OAAO,KAAa,YAAY,GAAmB;EACnD,IAAM,IAAS,GAC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,MAAM;IAAM,UAAU;IAAqC,GAG7D,EAAK;IAE3B,EAEK;IAGkC,EAAS,EAEmB,GAA6D,EAAW,EAG9I"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { default as migrate } from 'migrate-mongo';
|
|
2
2
|
import { default as mongooseRaw } from 'mongoose';
|
|
3
3
|
import { MongoController } from './mongo.controller.js';
|
|
4
|
-
import { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_MongoosePlugin, T_MongooseSchema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';
|
|
4
|
+
import { C_Document, I_CreateModelOptions, I_CreateSchemaOptions, I_DynamicVirtualOptions, I_ExtendedModel, I_GenericDocument, I_MongooseModelMiddleware, T_Filter, T_MongoosePlugin, T_MongooseSchema, T_QueryFilter, T_VirtualOptions, T_WithId } from './mongo.type.js';
|
|
5
5
|
/**
|
|
6
6
|
* Converts enum values to proper model names.
|
|
7
7
|
* Handles common naming conventions like converting 'USER' to 'User'.
|
|
@@ -40,8 +40,8 @@ interface I_MongoUtils {
|
|
|
40
40
|
};
|
|
41
41
|
regexify: <T>(filter?: T_QueryFilter<T>, fields?: (keyof T | string)[]) => T_QueryFilter<T>;
|
|
42
42
|
isDynamicVirtual: <T, R extends string>(options?: T_VirtualOptions<T, R>) => options is I_DynamicVirtualOptions<T, R>;
|
|
43
|
-
getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?:
|
|
44
|
-
getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?:
|
|
43
|
+
getNewRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T[]>;
|
|
44
|
+
getExistingRecords: <T extends I_GenericDocument>(controller: MongoController<T>, recordsToCheck: T[], filterFn: (existingRecord: T_WithId<T>, newRecord: T) => boolean, filter?: T_Filter<T>) => Promise<T_WithId<T>[]>;
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* MongoDB utility object providing comprehensive database operations and utilities.
|